janvladimirmostert
07/27/2022, 9:08 PMval a = fun (): String {
return ""
}
or
val a = fun () = ""
and lambda expression
val b: () -> String = {
""
}
or
val b = { "" }
in any way other than just the syntax?Raymond
07/28/2022, 3:02 AMdmitriy.novozhilov
07/28/2022, 7:11 AMreturn
in lambdas and functions means different things:
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
}
}
Zinedine Bedrani
08/05/2022, 11:25 PMjanvladimirmostert
08/08/2022, 8:25 PMZinedine Bedrani
08/09/2022, 9:09 PMval 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 🙏janvladimirmostert
08/09/2022, 9:34 PMval 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 impliedZinedine Bedrani
08/09/2022, 11:53 PMjanvladimirmostert
08/10/2022, 10:14 AMval s: String = {
if (a) {
"string1"
} else {
"string2"
}
}
s will contain either string1
or string2
depending on whether a
is true
or false