Home > Enterprise >  How to transform a list to an array in kotlin
How to transform a list to an array in kotlin

Time:04-20

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.

CodePudding user response:

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 asTransReward(): TransReward = TransReward(
     nameBefore = this.nameBefore,
     amountAfter = this.amountAfter
  )
}

// use it like this
val rewardArray : Array<TransReward> = rewardList.map{ it.asTransReward() }.toTypedArray()
  • Related