首页 > 解决方案 > 如何在 kotlin 中返回多个值?

问题描述

我想返回 4 个值(notDev、lastIndex、lastIndexValue、firstIndexValue)

我尝试了返回表达式并将有趣的输出更改为

fun whenNotZero(): (Int, Int, Int, Int) -> Unit{//rest of the code
return{notDiv, lastIndex, lastIndexValue, firstIndexValue}
}

然后我试着这样做

fun whenNotZero(order:Int): Int {//rest of the code
   if(order == 1){return notDiv}
   if(order == 2){return lastIndex}
   if(order == 3){return lastIndexValue}
   if(order == 4){return firstIndexValue}
}

有什么方法可以像 python 一样返回这些值或完全返回它们?

蟒蛇代码

def foo():
    # code here
    return(notDiv, lastIndex, lastIndexValue, firstIndexValue)
values = foo()
print(values[0])  

我当前的 kotlin 代码

fun whenNotZero() {
   val seq = mutableListOf<Int>()
   val inDevSeq = mutableListOf<Int>()
   for (i in range1..range2) {
       if (i % divisible_number == 0){inDevSeq.add(i);seq.add(i)}else{seq.add(i)}
   }

   val notDiv = seq.sum() - inDevSeq.sum()
   val lastIndex = inDevSeq.count()
   val lastIndexValue = inDevSeq.last()
   val firstIndexValue = inDevSeq.first()
}

标签: androidkotlin

解决方案


推荐阅读