Can you help me to understand, why we need anonymo...
# getting-started
a
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?)
Copy code
val tmp: InputType -> OutputType = { input -> output }
🤔
s
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.
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
Thanks)
u
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
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
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