-1

How to return from an anonymous lambda in Kotlin?

Somehow the complier doesn't allow to return inside the lambda body. Since the lambda is anonym an return@... isn't possible here.

class Foo {

    var function: (String) -> Unit = { _ -> }

    init {
        function = { text ->

            if (text == "foo"){
                // do side effects here
                return
                //'return' is not allowed here
                //This function must return a value of type Foo
            }
            // do side other side effects
        }
    }
}

EDIT: update the example so it is clear that this question is about the return statement and not coding practices

Chriss
  • 5,157
  • 7
  • 41
  • 75
  • 1
    Does this answer your question? [Using return inside a lambda?](https://stackoverflow.com/questions/45348820/using-return-inside-a-lambda) -> This also provides an explanation as to why – AlexT Oct 26 '20 at 13:57
  • No an anonymous function is different, a label is required as described in the accepted answer. – Chriss Oct 26 '20 at 14:06

2 Answers2

3

Use Label:

class Foo {

    var function: (String) -> Unit

    init {
        function = function@ { text ->
    
            if (text == "foo"){
                return@function
            }

            print(text)

        }
    }
}
Jiho Lee
  • 957
  • 1
  • 9
  • 24
1

While it's possible to do, I'm not a fan of that sort of thing and prefer to restructure the flow when practical. In your example, it would be something like:

function = { text ->
    if (text == "foo"){
        // do side effects here
    } else {
        // do side other side effects
    }
}

There are usually ways to keep the flow to a single return path, so you don't have to do strange things like have multiple return statements or use labels.

Adam Millerchip
  • 20,844
  • 5
  • 51
  • 74
  • Thanks for the feedback, I update the example so it is clear that my question is about the return statement and not coding practices. – Chriss Oct 28 '20 at 07:16
  • No problem. I updated the answer too, to demonstrate it's still not necessary to use `return`. – Adam Millerchip Oct 28 '20 at 07:56