How to convert function output to Unit with Kotlin

前端 未结 6 466
轻奢々
轻奢々 2021-01-12 11:48

I have troubles with a function in Kotlin that should return Unit, but due to a usage of another function returning a Boolean, there is a type mismatch.

Here is a co

6条回答
  •  醉酒成梦
    2021-01-12 12:09

    I think you should change return type of function to optional, it's more clear, like below:

    fun printAndReturnTrue(bar: Int): Boolean {
        println(bar)
        return true
    }
    
    fun foo(bar: Int): Unit? = when(bar) {
        0 -> println("0")
        else -> printAndReturnTrue(bar) as? Unit
    }
    

提交回复
热议问题