someone to tell me what is the receiver
in Kotlin? I checked the official documentation but I can't understand what it is.
Also you could tell me what function Int.
has in the following code:
Int.(Int, Float) -> Int
In general, the receiver is this
, the current instance.
In Kotlin, a lambda with receiver (which is what Int.(Int, Float) -> Int
is) is a way to define functions which act similar to methods of their receiver: They can reference the receiver with this
and can easily call other methods and properties of the receiver. (With the exception of private methods and properties.)
Here is some example code with the lambda type you gave, where the receiver is of type Int. The actual receiver instance is passed to invoke
as its first argument.
val lambdaWithReceiver: Int.(Int, Float) -> Int = { firstArgument, secondArgument ->
println("this = $this") // accessing this
println("this.toLong() = ${toLong()}") // calling Int's methods
println("firstArgument = $firstArgument")
println("secondArgument = $secondArgument")
this + 3
}
// passes 7 as the receiver, 3 and 2F as the arguments
val result = lambdaWithReceiver.invoke(7, 3, 2F)
println("result = $result")
The above snippet will print the following output:
this = 7
this.toLong() = 7
firstArgument = 3
secondArgument = 2.0
result = 10