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)
}
Android Kotlin sumOf maxOf minOf (3) | 2024.10.18 |
---|---|
Android Kotlin Activity 액티비티 (0) | 2024.10.15 |
Android Kotlin bindService LocalBinder (2) | 2024.09.25 |
Android Kotlin Context (3) | 2024.09.25 |
Android Kotlin Permission (0) | 2024.09.24 |
댓글 영역