is there a difference between anonymous function ...
# getting-started
j
is there a difference between anonymous function
Copy code
val a = fun (): String {
   return ""
}
or 
val a = fun () = ""
and lambda expression
Copy code
val b: () -> String = {
   ""
}
or
val b = { "" }
in any way other than just the syntax?
r
They have a difference that can’t noticed in your snippet. Lambdas cannot return locally unless inlined, whereas anonymous function do return locally. You can check the behavior on this sample: https://github.com/rayarteagas/Functional-programming-with-kotlin-talk/blob/main/src/main/kotlin/LambdasAndAnonymousFunctions.kt
d
If function is not inlined then local return is prohibited (unless function is inlined). But the thing is that
return
in lambdas and functions means different things:
Copy code
fun test(b: Boolean) { // (1)
    val function = fun () { // (2)
        if (b) return // return from (2), allowed
        if (b) return@test // return from (1), prohibited
    }

    val lambda: () -> Unit = l@{ // (3)
        if (b) return // return from (1), prohibited
        if (b) return@l // return from (3), allowed
    }
}
z
@janvladimirmostert Another thing is with anonymous functions you can have multiple returns 👍
j
how does one do multiple returns with an anonymous function other than Pair or Triple or a data class?
z
Wait, I think there is a misunderstanding, what I meant with anonymous functions you can have “Multiple return points” is that you can do something like:
val a = fun(str:String):String {
if(str.isEmpty())
return "String is empty"
else return str
}
But with lambda expression you can’t do that. correct me if I’m wrong please 🙏
j
you can definitely do it with lambdas too
Copy code
val l: (String) -> String = lambda@{ param: String ->
   if (param.isEmpty()) {
      return@lambda "String is empty"
   } else {
      return@lambda param
   }
}
or you can omit the
lambda@
and then omit the
return@lambda
and it will also return and you can also omit the
(String) -> String
since that's implied
K 1
z
This is because you’re using labels 😁 but if you don’t use it, compiler will tells you that return is not allowed here, am I wrong ? 😁
j
you don't need a return to return something
Copy code
val s: String = {
   if (a) {
       "string1"
    } else {
       "string2"
    }
}
s will contain either
string1
or
string2
depending on whether
a
is
true
or
false