What is difference between them as follows: ``` v...
# getting-started
j
What is difference between them as follows:
Copy code
val sum: Int.(Int) -> Int = { other -> plus(other) }
val sum = fun Int.(other: Int): Int = plus(other)
According to document(https://kotlinlang.org/docs/reference/lambdas.html#function-literals-with-receiver), when i use anonymous function,
The anonymous function syntax allows you to specify the receiver type of a function literal directly. This can be useful if you need to declare a variable of a function type with receiver, and to use it later.
. What does it mean? Why do i can’t use a variable of function type(not anonymous function but
val intPlus: Int.(Int) -> Int = Int::plus
) later?
d
The sentence means that inside the lambda ("anonymous function") you have a receiver (
this
) of type
Int
, which you can access. This is because the type of the lambda is specified as a "function with receiver".
j
@diesieben07 Sorry, at first I wrote wrong code snippet. Now, i fixed the code snippet. I want to know why is using anonymous function only useful(
to use it later
)? Using lambda, we can’t do that?
k
I don't get it either, they present it as an advantage of the second syntax but as far as I know they're equivalent.
👍 1
d
When using a reference to an existing function, the "function-with-receiver" type can be inferred. When using a lambda, it cannot, so if you want to do that, you need to specify the type. That's what I am gathering from it.
👍 1
"Use it later", because if you just call a method which has a parameter of such a function-with-receiver type, the type will be known and inferred for your lambda.
j
Ah thanks~ @karelpeeters @diesieben07