Home > Net >  Return two values from for loop in Kotlin
Return two values from for loop in Kotlin

Time:07-08

I am trying to return two values from the array with the for loop, but am only getting the first value instead.

data class Batches(
    var qty: Int?,
    var entries: List<TruckEntry>?,
    var entryIds: ArrayList<String>?,
    var priceconfig: PriceConfig?

) {
    constructor() : this(0, null, null, null)
}

data class TruckEntry(var name: String?, var id: String?, var qty: Int?, var observed: Int?) {
    constructor() : this(null, null, null, null)
}

My function:

private fun getBatchName(batches: Batches): String? {
                  if (!batches.entries.isNullOrEmpty()) {
                    val entrySize = arrayOf(batches.entries!!)
                    for(index in 0..entrySize.size - 1){
                        return batches.entries!![index].name
                    }
                }
                      return "****************"

    }

CodePudding user response:

Return always exits the function with a value or null. You need to store the value found inside the loop in a variable and return it at the end of the function with the other value you want.

I'm not a kotlin programmer, so here is a pseudo code which might help you.

//A class that will hold your return values
//as you can only return one value from a function once

class Holder{
  constructor(data1, data2){
    this.returnValue1 = data1
    this.returnValue2 = data2
  }
}
function yourFunction(batches){
  var data1
  var data2 = "whatever"
  
  for( batch in batches ){
    if( condition ){
      data1 = batch
      break
    }
  }

  return new Holder(data1, data2)
}

Also when accessing this values from another functions/classes you need to access these according to your Holder class. Like

var returnVal = yourFunction(batches)
var val1 = returnVal.returnValue1

CodePudding user response:

If you want to return more than one thing from a function, you need to return something that can hold multiple values, such as a Pair, Triple, or List. List makes the most sense in this case since you don't know for sure how many values there will be.

Example:

private fun getBatchNames(batches: Batches): List<String?> {
    return batches.entries.orEmpty()
        .map { it.name }
}
  • Related