Rahul
Rahul

Reputation: 755

How to return from Kotlin function type

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

Answers (2)

Alex Romanov
Alex Romanov

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 a return statement is called a non-local return, because it returns from a larger block than the block containing the return statement.

The rule is simple: return returns from the closest function declared using the fun keyword. Lambda expressions don’t use the fun keyword, so a return in a lambda returns from the outer function.

Upvotes: 2

holi-java
holi-java

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

Related Questions