Kotlin - 匿名函式與函式型別
匿名函式
package examples
fun main() {
var f = {
println("hello")
}() // print hello
}
函式型別
package examples
fun main() {
{
println("construstor ")
}()
var f = {
println("hello f1")
}
val f2: () -> Unit = {
println("hello f2")
}
f()
f2()
}
隱式回傳
- 匿名函式支援回傳最後一行的值
package examples
fun main() {
var f = { //
"implicit return"
"ABC" // Print ABC
}
println(f())
}
匿名函式參數
package examples
fun main() {
// arg types return type arg names
val f : (String, String, String) -> Int = {a, b, c ->
a.length + b.length + c.length
}
println(f("aa", "fff", "ee"))
}
預設參數名稱:it
- 當匿名函式只有一個參數時,"it" 就是預設的參數名稱
package examples
fun main() {
val f : (String) -> Int = {
it.length
}
println(f("Gss"))
}
回傳型別推斷
- 不需要指定回傳型別
package examples
fun main() {
val f = {
"hello"
}
println(f())
}
- 沒有指定回傳型別時,需要提供參數名稱
package examples
fun main() {
val f = { name:String ->
"hello $name"
}
println(f("FF"))
}
函式作為參數
package examples
fun main() {
println(count("hello", {it == 'l'}))
}
fun count(s:String, exclude:(Char) -> Boolean): Int {
var result = 0
for (c in s) if (!exclude(c)) result++
return result
}
- Lambda 參數應該移到括號外面(IntelliJ 建議)(當函式是最後一個參數時)
package examples
fun main() {
println(count("hello") {it == 'l'})
}
fun count(s:String, exclude:(Char) -> Boolean): Int {
var result = 0
for (c in s) if (!exclude(c)) result++
return result
}
函式 Inlining
- Inlining 可以避免 JVM 為 lambda 建立物件實例和進行變數記憶體配置。
package examples
fun main() {
println(count("hello") {it == 'l'})
}
inline fun count(s:String, exclude:(Char) -> Boolean): Int {
var result = 0
for (c in s) if (!exclude(c)) result++
return result
}
函式參考
- 使用 "::" 來參考一個函式
package examples
fun main() {
run(::printHello)
}
fun run(f: () -> Unit) {
f()
}
fun printHello() {
println("hello")
}
回傳函式型別
package examples
fun main() {
create()("john")
}
fun create(): (String) -> Unit {
return {
println("hello $it")
}
}