Hello all, I’m trying to do something I usually do...
# announcements
c
Hello all, I’m trying to do something I usually do on JS that follow something like this:
Copy code
const 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 properties
s
Isnt that just a map ?
c
you can do it with a map, but not an object, so
Copy code
kotlin
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 storage
unless you are running kotlin on the JS runtime as opposed to JVM or native, in which case there's a single exception for
dynamic
type, but I don't know too much of how it works. should be somewhere in the documentation
p
by using the
dynamic
keyword you tell the compiler to literally insert whatever you write (it has to be valid js). There is no hidden magic or anything.
Copy code
class 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
the same can be done in the foreach, in principle. In an actual project you should never do this, because you give up all typesafety and you can run into nasty errors e.g. imagine if Person inherited from a class which already defined a property called name, but that property was a custom type not a String