Can you help me to understand, why we need anonymous functions?)
There are sentence in documentation it's suppose to explain that, but I do not understand it either.
In lambda expression we can specify and input type, and output type, don't we?)
Well, in your code example, there are two parts. The bit on the right,
{ input -> output }
, is the lambda expression. The
InputType -> OutputType
on the left is the type declaration. The lambda expression alone doesn't have the ability to specify a return type. But it doesn't need to when it's used in conjunction with an explicit type declaration.
Sam
07/09/2024, 10:43 AM
I guess the docs are saying that anonymous functions let us specify a return type in the expression itself, which would be useful if we need to create a function without an explicit type declaration. I've never encountered that situation in all my years of writing Kotlin, though.
a
Anatoly
07/09/2024, 10:44 AM
Thanks)
u
Ulrich Schuster
07/09/2024, 1:34 PM
An anonymous function function simply is a function not bound to a name. They are useful whenever first declaring a function type with name is superfluous – as in lambdas. Thus, the prime use of anonymous functions is in lambdas
s
Sam
07/09/2024, 2:05 PM
Well, it's true that a lambda is a function without a name, but Kotlin uses the term "anonymous function" to refer to something specific, different from a lambda. The docs mentioned in the question are specifically about this anonymous function syntax, as opposed to lambda expressions.
Copy code
val lambda = { s: String -> s.length }
val anonymousFunction = fun(s: String): Int = s.length
u
Ulrich Schuster
07/09/2024, 3:13 PM
Ah, I didn't know about that rather unconventional differentiation, thanks for pointing it out. So in Kotlin speak, an anonymous function is a function bound to a val – which is od, because a value is some object in memory bound to a name; i.e. not anonymous at all