import kotlin.math.PI

//Functions 함수

//함수 선언할때는 fun keyword를 사용한다.
fun hello() {
    return println("Hello, world!")
}

//x, y는 함수의 파라미터이고 Int타입. return타입 또한 Int타입.
/*fun sum(x: Int, y: Int): Int {
    return x + y
}*/
//위의 함수를 Single-expression function으로 바꾸면
fun sum(x: Int, y: Int) = x + y
//이렇게 할 수 있음. 대괄호를 없애고 할당연산자 = 를 통해 함수몸체를 선언한다. 코틀린의 type inference덕분에 return type또한 제거할 수 있다.

//Named arguments, Default parameter values
//파라미터에 이름을 붙이면 코드의 가독성이 좋아짐
fun printMessageWithPrefix(message: String, prefix: String = "Info") {
    println("[$prefix] $message")
}

//Return이 없는 함수
fun printMessage(message: String) {
    println(message)
    // `return Unit` or `reutnr` is optional
    //함수에서 return value가 없으면 그 함수의 return type은 Unit이다. Unit은 오직 하나의 value를 갖는 type이다.
    //함수 몸체 안에 명시적으로 선언할 필요가 없다.
}

fun main() {
    hello()
    println(sum(1, 2))
    printMessageWithPrefix("Hello, world!", "Greeting")
    //named arguments를 통해 직접 할당하게 되면 파라미터의 순서를 바꿀 수 있다.
    printMessageWithPrefix(prefix = "Log", message = "Hello")
    //prefix는 default value를 주어서 파라미터를 안넘기면 기본값이 출력된다.
    printMessageWithPrefix("This is a custom message.")
    //[Info] This is a custom message.

    //return이 없는 함수
    printMessage("This function doesn't have return type.")
}


fun circleArea(radius: Int)  =  radius * radius * PI

https://kotlinlang.org/docs/kotlin-tour-functions.html#lambda-expressions

 

Functions | Kotlin

 

kotlinlang.org

 

'정보 > Language' 카테고리의 다른 글

[Javascript] Object, Array  (0) 2024.01.09
Kotlin: Control Flow  (0) 2023.07.31
Kotlin : Hello, world!  (0) 2023.07.20
Enum을 사용한 메뉴관리  (0) 2022.08.26
java.util.HashMap  (0) 2022.07.29

+ Recent posts