Saraladewi
Saraladewi

Reputation: 117

How to pair values in kotlin array?

I have a class with 2 property

class SelectedAmount : Serializable {
    lateinit var amount: List<Int> //the values here is coming from backend in array list. eg [50,100,150,200]
    var isSelect: Boolean = false
}

I want to pair each amount with a boolean value. eg [{50, true}, {100, false}, {150, false}, {200, false}]

In view activity i did

private var amountList: MutableList<AmountSelected> = ArrayList<AmountSelected>()
val amountInterval = data.reloadDenoms // BE value {50,100,150,200}
if (amountInterval != null) {
  for (items in amountInterval) {
  var amountSelected:SelectedAmount = SelectedAmount()
  amountSelected.amount = amountInterval
  amountSelected.isSelect = false // tring to set boolean false for every amountInterval value
  amountList.add(amountSelected)
}

when i tring to print the value of amountList .. i get out put as

[{50,100,150,200}, false]

my expected output is

[{50, true}, {100, false}, {150, false}, {200, false}]

can anyone help me on this? I am a newbie here learning array btw

Upvotes: 1

Views: 905

Answers (2)

Ananiya J. Kesto
Ananiya J. Kesto

Reputation: 1364

The easier approach I got

listOf(50,100, 150, 200).map { 
        it to (it % 100 != 0)
    }.let {
        print(it)
    }

Upvotes: 0

Indra Kumar S
Indra Kumar S

Reputation: 2935

No need of List of integers in SelectedAmount

class SelectedAmount : Serializable {
    lateinit var amount: int //the values here is coming from backend in array list. eg [50,100,150,200]
    var isSelect: Boolean = false
}

And

// *** Note the SelectedAmount instead of AmountSelected
    private var amountList: MutableList<SelectedAmount> = ArrayList<SelectedAmount>() 
    val amountInterval = data.reloadDenoms // BE value {50,100,150,200}
    if (amountInterval != null) {
      for (items in amountInterval) {
      var amountSelected:SelectedAmount = SelectedAmount()
      amountSelected.amount = items // **Add only the integer** You were adding the list earlier
      amountSelected.isSelect = true // **You can set boolean for one or more items if needed**
      amountList.add(amountSelected)
    }

Upvotes: 1

Related Questions