簡體   English   中英

如何配對 kotlin 數組中的值?

[英]How to pair values in kotlin array?

我有一個具有 2 個屬性的 class

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
}

我想將每個金額與 boolean 值配對。 例如 [{50, true}, {100, false}, {150, false}, {200, false}]

在視圖活動中我做了

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)
}

當我試圖打印amountList的值時 .. 我輸出為

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

我預期的 output 是

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

誰可以幫我這個事? 我是這里的新手學習數組順便說一句

不需要 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
}

// *** 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)
    }

我得到的更簡單的方法

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM