'How to transform a list to an array in kotlin
I have a list
val rewardList: List<Reward>
class Reward(
val nameBefore: String
val amountBefore: Long
)
I want to have
val rewardArray: Array<TransReward>
class TransReward(
val nameAfter: String
val amountAfter: Long
)
There is name mapping involved and I can't figure out a good way to change list to array.
P.S. The class design is previous code in the system so I can't change it.
Solution 1:[1]
To transform List to Array you could use .toTypedArray(),but in your case you can't transform List<Reward> to Array<TransReward> because the class type are different.
My solution is to transform your Reward to TransReward first and then use .toTypedArray()
val rewardList: List<Reward>
class Reward(
val nameBefore: String?
val amountBefore: Long
){
fun toTransReward(): TransReward = TransReward(
nameAfter = this.nameBefore,
amountAfter = this.amountBefore
)
}
// use it like this
val rewardArray : Array<TransReward> = rewardList.map{ it.toTransReward() }.toTypedArray()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
