Search code examples
kotlindata-class

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


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, ...]

Solution

  • 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