Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

P.S. The class design is previous code in the system so I can’t change it.

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading