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
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
}
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.