简体   繁体   中英

Kotlin: Recursion using “when”

I've been trying to do recursion with "when" in Kotlin, and indeed, it works, but it also gives me some strange outputs with void datatype, known in Kotlin as Unit, how does "when" statement work? Does it have to return something?

fun pick(camara: Boolean, klinga: Boolean){
    when {
         camara -> println("KLINGA")
         klinga -> println("CAMARA")
         else -> println(pick(Random.nextBoolean(), Random.nextBoolean()))
    }
}    

pick(false, false)

it returns:

CAMARA
kotlin.Unit
kotlin.Unit
kotlin.Unit

The recursion is correctly made but it also outputs void data (probably corresponding to the number of recursion calls)

So the question is, why does this kind of output appears? Is it because "when" returns the returned value of the function call? In this case Unit?

Functions that don't return anything actually return Unit . Your function the same as

fun pick(camara: Boolean, klinga: Boolean): Unit {...}

Possible solutions:

tailrec fun pick(camara: Boolean, klinga: Boolean) {
    when {
        camara -> println("KLINGA")
        klinga -> println("CAMARA")
        else -> pick(Random.nextBoolean(), Random.nextBoolean())
    }
}

fun main() {
    pick(false, false)
}

or

tailrec fun pick(camara: Boolean, klinga: Boolean): String = 
    when {
        camara -> "KLINGA"
        klinga -> "CAMARA"
        else -> pick(Random.nextBoolean(), Random.nextBoolean())
    }

fun main() {
    println(pick(false, false))
}

tailrec for optimizations of Tail recursive functions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM