2019年4月28日日曜日

Kotlin - lambdas and higher-order functions - Treating Code Like Data - type

Head First Kotlin: A Brain-Friendly Guide (Dawn Griffiths(著)、David Griffiths(著)、O'Reilly Media)のChapter 11(lambdas and higher-order functions - Treating Code Like Data)、WHAT'S MY TYPE?の解答を求めてみる。

コード

```fun main() {
println("lambda1")
var lambda1: (Double) -> Int
// 代入できるのはない

println("lambda2")
var lambda2: (Int) -> Double

lambda2 = { it + 7.1 }
println(lambda2(10))

println("lambda3")
var lambda3: (Int) -> Int

lambda3 = { (it * 3) - 4 }
println(lambda3(10))

lambda3 = { x: Int -> x + 56 }
println(lambda3(10))

println("lambda4")
var lambda4: (Double) -> Unit

lambda4 = { it + 7.1 }
println(lambda4(1.2))

lambda4 = { (it * 3) - 4 }
println(lambda4(1.2))

lambda4 = { println("Hello!") }
println(lambda4(1.2))

lambda4 = { x: Double -> x + 75 }
println(lambda4(1.2))

println("lambda5")
var lambda5 = { x: Int -> x + 56 }
println(lambda5(10))

var lambda5_1 = { println("Hello!") }
println(lambda5_1.invoke())

var lambda5_2 = { x: Double -> x + 75 }
println(lambda5_2(1.2))
}```

```lambda1
lambda2
17.1
lambda3
26
66
lambda4
kotlin.Unit
kotlin.Unit
Hello!
kotlin.Unit
kotlin.Unit
lambda5
66
Hello!
kotlin.Unit
76.2

Process finished with exit code 0
```