How to convert function output to Unit with Kotlin

I have problems with a function in Kotlin that should return Unit, but due to using another function that returns a boolean, there is a type mismatch.

Here is a contrived example:

fun printAndReturnTrue(bar: Int): Boolean {
    println(bar)
    return true
}

fun foo(bar: Int): Unit = when(bar) {
    0 -> println("0")
    else -> printAndReturnTrue(bar)
}

Here, I really don't care about what printAndReturnTruereturns a boolean. I just want foo to do side effects. But the compiler warns of type mismatch: my elseshould return a value Unit.

Is there a good way to convert a value to Unit?

The simplest solutions that I see are as follows:

fun foo(bar: Int): Unit = when(bar) {
    0 -> println("0")
    else -> { 
        printAndReturnTrue(bar)
        Unit
    }
}

or

fun foo(bar: Int): Unit = when(bar) {
    0 -> println("0")
    else -> eraseReturnValue(printAndReturnTrue(bar))
}

fun eraseReturnValue(value: Any) = Unit

Or I use the full form of the function:

fun foo(bar: Int): Unit { 
    when(bar) {
        0 -> println("0")
        else -> printAndReturnTrue(bar)
    }
}

I'm sure there are some idiomatic ways to do this (or is this the last example?), But so far I have not found them.

+4
5

, . , (T) -> Boolean , (T) -> Unit lambdas, , - .

when, Unit:

fun Any?.toUnit() = Unit

fun foo(bar: Int): Unit = when(bar) {
    0 -> println("0")
    else -> printAndReturnTrue(bar)
}.toUnit()

, , , :

val Any?.unit get() = Unit

fun foo(bar: Int): Unit = when(bar) {
    0 -> println("0")
    else -> printAndReturnTrue(bar)
}.unit

, Unit, .

+7

, . : Unit, , , - , .

: when , else , , ; " ", .

+3

, , :

fun consume (fn: () -> Any): Unit {
  fn()
}

Donation:

fun foo(bar: Int): Unit = when(bar) {
    0 -> println("0")
    else -> consume { printAndReturnTrue(bar) }
}
+1
source

I think you should change the return type of the function to optional, this is more clear, as shown 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
}
0
source

I just use a semicolon if I write in a string.

someExpression; Unit
0
source

Source: https://habr.com/ru/post/1689510/


All Articles