I have a data class
which has a constructor
like this (source):
data class MyDataClass (
val myArr: ArrayList<Char>
) {
constructor(n: Int):
this(
ArrayList((0 until n).map { ('A' + it).toChar() })
)
}
As an example:
println(MyDataClass(3).myArr)
would give me:
[A, B, C]
I want to modify my data class
further like this:
data class MyDataClass (
val myArr: ArrayList<Char>,
val myMap: MutableMap<Char, MutableMap<String, String>>
) {
constructor(n: Int):
this(
ArrayList((0 until n).map { ('A' + it).toChar() }),
mutableMapOf()
)
}
Now, when I print the myMap
like:
println(MyDataClass(3).myMap)
I get:
{}
Now, I want that instead of getting an empty MutableMap
for myMap
, I want to get a MutableMap
like this:
println(MyDataClass(3).myMap)
{A={}, B={}, C={}}
How would I do that?
You can do one of the following:
data class MyDataClass(
val myArr: ArrayList<Char>,
val myMap: MutableMap<Char, MutableMap<String, String>>
) {
constructor(n: Int) : this(
ArrayList(foo(n)),
foo(n).map { it to mutableMapOf<String, String>() }.toMap().toMutableMap()
)
companion object {
fun foo(n: Int) = (0 until n).map { ('A' + it) }
}
}
data class MyDataClass(
val myArr: ArrayList<Char>,
val myMap: MutableMap<Char, MutableMap<String, String>>
) {
constructor(n: Int) : this(ArrayList((0 until n).map { ('A' + it) }))
constructor(list: ArrayList<Char>) : this(
list,
list.map { it to mutableMapOf<String, String>() }.toMap().toMutableMap()
)
}