how to break from lambda passed to recursive function when provided condition met

后端 未结 2 1280
时光取名叫无心
时光取名叫无心 2021-01-28 11:50

I am writing a custom loop dsl and I want it\'s usage to look like below


    var counter1 = 0
    var counter2 = 0
    loop {
            counter1          


        
2条回答
  •  抹茶落季
    2021-01-28 12:38

    It can be done for example with throwing a lightweight exception. You have to declare custom exception:

    class LoopStopException : Throwable("Stop look", null, false, false) // lightweight throwable without the stack trace
    

    and catch it in loopWithoutDelay:

    private suspend fun loopWithoutDelay(block: suspend () -> Unit) {
        try {
            while (true) {
                block()
            }
        } catch (e: LoopStopException) {
            //do nothing
        }
    }
    
    

提交回复
热议问题