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.