Christian Sousa
03/18/2020, 1:00 PMconst myArray = ['1', '2', '3']
let myObj = {
default = '0'
}
myArray.forEach(elem => {
myObj = {
...myObj,
[`newProperty-${elem}`] = elem
}
})
Is there any way to do something like that in Kotlin?
Basically, I just need a way to create an object with a variable amount of propertiesspand
03/18/2020, 1:29 PMcypher121
03/18/2020, 2:01 PMkotlin
val myArray = listOf(1, 2, 3)
val map = mutableMapOf("default" to 0)
myArray.forEach {
map += "newProperty-$it" to it
}
mind that in statically typed OOP languages like java or kotlin, objects strictly conform to their class definition, so you can't just remove or add properties at runtime. that's only for maps, which are just a key-value storagecypher121
03/18/2020, 2:03 PMdynamic
type, but I don't know too much of how it works. should be somewhere in the documentationpatrickdelconte
03/19/2020, 1:09 PMdynamic
keyword you tell the compiler to literally insert whatever you write (it has to be valid js). There is no hidden magic or anything.patrickdelconte
03/19/2020, 1:13 PMclass Person {}
// add a property to Person, works only in JS land
var Person.name: String
get = this.asDynamic().name
set(value) this.asDynamic()["name"] = value
patrickdelconte
03/19/2020, 1:19 PM