Reputation: 755
I'm using function type to store code to be invoked on button click.
How to return from this function type
Code given below :
var SearchClickEvent: ((searchString: String) -> Unit)? = null
inputDialog!!.SearchClickEvent = Search_Click
private val Search_Click = { searchString: String ->
if(searchString.isEmpty()){
return//Error msg : return is not allowed here
//How to return from here
}
}
NOTE: I'm storing a piece of code in a variable not calling or writing any function
Upvotes: 7
Views: 2134
Reputation: 11963
You can also do it like this:
private val Search_Click =
fun(searchString: String) {
if (searchString.isEmpty()) return
// more code
}
Kotlin in Action:
If you use the
return
keyword in a lambda, it returns from the function in which you called the lambda, not just from the lambda itself. Such areturn
statement is called a non-local return, because it returns from a larger block than the block containing thereturn
statement.The rule is simple:
return
returns from the closest function declared using thefun
keyword. Lambda expressions don’t use thefun
keyword, so areturn
in a lambda returns from the outer function.
Upvotes: 2
Reputation: 30686
you need to create a label with explicit return statement in lambda, for example:
// label for lambda---v
val Search_Click = action@{ searchString: String ->
if (searchString.isEmpty()) {
return@action;
}
// do working
}
OR invert the if statement as below:
val Search_Click = { searchString: String ->
if (!searchString.isEmpty()) {
// do working
}
}
Upvotes: 11