简体   繁体   English

Kotlin:使用“何时”进行递归

[英]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?我一直在尝试使用 Kotlin 中的“何时”进行递归,实际上,它确实有效,但它也给了我一些奇怪的输出数据类型为 void,在 Kotlin 作为单位中已知,“何时”语句如何工作? 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?那么问题来了,为什么会出现这种output呢? Is it because "when" returns the returned value of the function call?是不是因为“when”返回了 function 调用的返回值? In this case Unit?在这种情况下单位?

Functions that don't return anything actually return Unit .不返回任何内容的函数实际上返回Unit Your function the same as你的 function 一样

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 tailrec用于优化尾递归函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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