Hello all, I’m trying to do something I usually do...
# announcements
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 = {
    [`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
Isnt that just a map ?
you can do it with a map, but not an object, so
Copy code
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
type, but I don't know too much of how it works. should be somewhere in the documentation
by using the
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