Receiver Type of function literals / anonymous function

Hello,

I have a hard time understanding the nuance of this part of the documentation. Particularly

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 then to use it later.

AFAIK the 2 examples provided are fully equivalent to me.

val sum: Int.(Int) -> Int = { other -> plus(other) }
val sum = fun Int.(other: Int): Int = this + other

So what does The anonymous function syntax allows you to specify the receiver type of a function literal directly reallymean ? What is in this first example make the receiver not typed ?

Any simple example where the first syntax is a problem vs the 2nd one ?

Thanks!

“directly” there refers to the fact that you can write that fun Int., while in your lambda example, you can’t specify the receiver directly, but only thru type hints (as you’ve done). Compare that to the fact that you can specify argument types directly: { foo: Int -> foo }

1 Like

Thanks. What you call type hintsis Int.(Int) -> Int ?

What bugs me, is that I don’t see the limitation to use the 1st vs the the 2nd ?

I can write val sum = Int.(Int) -> Int = { other -> this + other }, which is very equivalent (for me) to val sum = fun Int.(other: Int): Int = this + other, no ?

One is a lambda and the other is an anonymous function. From earlier in the doc:

Another difference between lambda expressions and anonymous functions is the behavior of non-local returns. A return statement without a label always returns from the function declared with the fun keyword. This means that a return inside a lambda expression will return from the enclosing function, whereas a return inside an anonymous function will return from the anonymous function itself.

Of course, but that does not really answer the point regarding the receiver type.

Just pointing out that those two statements aren’t equivalent.

To get back to your original question, I think the word “directly” is the important one. A lambda doesn’t allow you to specify that it takes a receiver – you can assign it to a variable whose type is a function with receiver, or pass it as an argument of that type, but you have to infer its type from where it’s used. But an anonymous function requires you to specify the type “directly” in its declaration.

1 Like

Or to put it another way, in the examples above, for the lambda you have to specify the variable’s type, while for the anonymous function the compiler can infer it.

Got it! Many thanks for taking the time ! I must say that the wording is a bit ambiguous here IMO :slight_smile: