A format,
1.1 Complete Format
// Kotlin
val sum: (Int.Int) - >Int = { x: Int, y: Int -> x + y}
// Groovy
Closure sum = { Integer x, Integer y -> x + y }
Copy the code
Kotlin’s function types are variable, e.g. (Int, Int) -> Int) Groovy’s function types have only one Closure
1.2 Simplified Format
// kotlin
val sumSimple1: (Int.Int) - >Int = { x, y -> x + y }
val sumSimple2 = { x: Int, y: Int -> x + y }
// groovy
sumSimple = { x, y -> x + y }
Copy the code
Kotlin’s lambda cannot completely omit type declarations when assigning a variable. When used as an argument to a function, it can be omitted. The def of Groovy can also be omitted; the val of Kotlin cannot
Second, the trailing lambda
When the last argument to a function is a function type, the lambda expression can be taken out of the argument list.
2.1 Three Parameters
// kotlin
fun a3(x: Int, y: Int, lambda: (Int.Int) -> Int) :Int {
return lambda(x, y)
}
val b = a3(1.2, { x, y -> x + y })
val bOut = a3(1.2) { x, y -> x + y }
// Groovy
def a3(def x, def y, Closure closure) {
closure(x, y)
}
a3(1.2, { x, y -> x + y })
a3(1.2) { x, y -> x + y }
Copy the code
2.2 A Parameter
// Kotlin
fun a1(lambda: (Int.Int) -> Int) :Int {
return lambda(1.2)}val bOut2 = a1 { x, y -> x + y }
// Groovy
def a1(Closure closure) {
closure(1.2)
}
a1 { x, y -> x + y }
Copy the code
Third, it
When lambda has only one argument, it can be used to represent it.
3.1 as input parameter
// Kotlin
fun itFun(lambda: (Int) -> Unit) {
lambda(1)}val itResult = itFun { print(it) }
// Groovy
def itFun(Closure closure) {
closure(1)
}
itResult = itFun { println(it) }
Copy the code
3.2 Assigning values to variables
// Kotlin
val it: (Int) - >Unit = { println(it) }
// Groovy
it = { println(it) }
Copy the code
When Kotlin’s lambda is assigned to a variable, the type needs to be declared.
The return value of lambda
The value of the last expression in a lambda expression is the return value
// Kotlin
val retLambda = {
1 + 1
3
}
val retVal = retLambda() / / value is 3
// Groovy
retval = {
1+1
3
}
retval() / / value is 3
Copy the code
5. Handling of useless variables
// Kotlin
val map = mapOf(1 to "a".2 to "b")
map.forEach { _, value -> print(value) }
// Groovy
map = [1: "a".2: "b"]
map.each { _, value -> println(_ + value) }
Copy the code
Kotlin’s _ can be used as a declaration of useless variables, just placeholder, not referable; Groovy’s _ is considered a normal declaration and can be referenced.
Access to external variables
Can access and modify objects outside of lambda expressions
// Kotlin
val ints = listOf(1.2.3)
var sum = 0
ints.filter { it > 0 }.forEach {
sum += it
}
println(sum) / / 6
// Groovy
ints = [1.2.3]
sum = 0
ints.findAll { it > 0 }.each {
sum += it
}
println(sum) / / 6
Copy the code
Seven, invoke
Kotlin’s lambda can be called with invoke(); Groovy doesn’t write this way.
// Kotlin
val sum = { x: Int, y: Int -> x + y }
sum.invoke(1.2)
sum(1.2)
// Groovy
sum = {x, y -> x + y}
sum(1.2)
Copy the code