【Kotlin】Kotlin 2.2.0 文档阅读

【Kotlin】Kotlin 2.2.0 文档阅读

本文记录了在阅读Kotlin 2.2.0官方文档过程中的之前遗漏的内容,并且更加全面地了解Kotlin编译器的跨平台相关内容

原文链接:

Kotlin Language Documentation 2.2.0

查漏补缺

lambda作为函数参数类型

这个操作平时使用较少,将lambda作为返回参数类型的场景。例如:

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

fun main() {
println(upperCaseString("hello"))
// HELLO
}

将一个字符串对象全部转换为大写,将 upperCaseString 声明为lambda类型,就可以作为参数传递。

另外一种用法是作为返回的参数类型。

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")
// Total time is 1680 secs
}

toSeconds 函数会根据传入的用法名称,返回一个lambda类型的函数,该函数将一个Int类型的参数转换为另一个Int类型的参数。

页码92

Multiplatform