https://kotlinlang.org logo
#getting-started
Title
# getting-started
j

janvladimirmostert

07/27/2022, 9:08 PM
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

Raymond

07/28/2022, 3:02 AM
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

dmitriy.novozhilov

07/28/2022, 7:11 AM
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

Zinedine Bedrani

08/05/2022, 11:25 PM
@janvladimirmostert Another thing is with anonymous functions you can have multiple returns 👍
j

janvladimirmostert

08/08/2022, 8:25 PM
how does one do multiple returns with an anonymous function other than Pair or Triple or a data class?
z

Zinedine Bedrani

08/09/2022, 9:09 PM
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

janvladimirmostert

08/09/2022, 9:34 PM
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

Zinedine Bedrani

08/09/2022, 11:53 PM
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

janvladimirmostert

08/10/2022, 10:14 AM
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