How to set values to data class if some size is specified in kotlin?

懵懂的女人 提交于 2019-12-24 19:42:58

问题


I have a data class in kotlin like this:

data class myDataClass(val myArr: ArrayList<Char>)

Now, suppose I create an instance of it as follows:

val myData = myDataClass(x)    // x is an integer; 1 <= x <= 9

I want that myData should have the following data:

println(myData.myArr)
// [A, B, C, D, ...]

回答1:


It's possible:

data class myDataClass(val myArr: ArrayList<Char>) {
    constructor(i: Int) : this(ArrayList((0..i).map { ('A' + it).toChar() }))
}

But the truth is, it's a pretty strange code



来源:https://stackoverflow.com/questions/57514143/how-to-set-values-to-data-class-if-some-size-is-specified-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!