Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return from Kotlin function type

Tags:

android

kotlin

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

like image 717
Rahul Avatar asked Jun 27 '17 04:06

Rahul


1 Answers

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
    }
}
like image 81
holi-java Avatar answered Oct 11 '22 05:10

holi-java