Android Kotlin

Kotlin 다양한 함수 Lambda Single-expression

신농해태 2024. 10. 15. 23:06
반응형

1. Default function

fun printMessageWithPrefix(message: String, prefix: String = "Info") {
    println("[$prefix] $message")
}

fun main () {
    printMessageWithPrefix("Hello", "Log")
    printMessageWithPrefix("Hello")

}

 

2. Single-expression Function

fun intervalInSeconds(hours: Int, minutes: Int, seconds: Int) = 
    ((hours*60) + minutes) * 60 + seconds

fun main () {
    println(intervalInSeconds(1, 20, 15))

}

 

3. Lambda expression function

fun main() {
    val upperCaseString = { text: String -> text.uppercase()}
    println(upperCaseString("hello"))

}

 

4. Collector에서 사용가능 함수
    val numbers = listOf(1, -2, 3, -4, 5, -6)
    val doubled = numbers.map { x -> x * x}
    println(doubled)

 

5. function type

val upperCaseString: (String) -> String = {text -> text.uppercase()}

fun main() {

    println(uppercaseString("hello"))

}

 

6. function을 return

fun toSeconds(time: String): (Int) -> Int = when (time) {
    "hour" -> {value -> value *60*60}
    "minute" -> { value -> value * 60}
    "second" -> {value -> value}
    else -> {value -> value}
}

fun main() {

    val timesInMinutes = listOf(2,10,15,1)
    val min2sec = toSeconds("minute")
    val totalTimeInSeconds = timesInMinutes.map(min2sec).sum()
    println("Total time is $totalTimeInSeconds secs")   

}

 

7. Invoke Lambda expression

fun main() {

    println( {text: String -> text.uppercase()}("hello") )

}

 

8. Trailing Lambda

fun main() {

    val numberss = listOf(1,2,3,4,5)
    val sumNumberss = numberss.fold(0) { y, x -> y + x }
    println(sumNumberss)

}

 

728x90
LIST