https://kotlinlang.org logo
Title
j

johnfn

02/17/2020, 10:07 PM
is there any way to get the type of an anonymous object? e.g. if i do
object { val x = 1 }
and then i want to make a list of them, how would i write it? ideally, something that i could put in ???
class Foo {
  private val myList = mutableListOf<???>()
  private fun addItem(x: Int) =
    myList.add(
      object { val x = x }
    )
}
s

Shawn

02/17/2020, 11:01 PM
Any
👍 1
anonymous objects that don’t explicitly implement an interface or extend a class will just inherit from
Any
like everything does by default
but that won’t let you access your
x
val
if all the objects you’ll have in that list have the same shape (i.e. the same properties/functions defined on them), then you can declare an interface and have the objects implement them (or just declare and instantiate data classes)
if that doesn’t match your use case and you just want arbitrary mappings between keys and values, use a
Map
but you’ll never be able to have a strongly typed, arbitrarily-defined object anywhere that’s not within the scope of a function
👍 1
c

Chenn

02/18/2020, 8:25 AM
val obj = js("{}")
    obj["type"] = type
This is how I put a key - value pair in an anonymous object in kotlin. Maybe it helps.
val obj: dynamic = object{}
    reducers.forEach { obj[it.key] = it.value}
This practically generates the same code..
s

Shawn

02/18/2020, 3:59 PM
is that for Kotlin/JS?
js()
isn’t a stdlib function and
dynamic
isn’t a standard type on JVM, and presumably elsewhere
c

Chenn

02/18/2020, 4:01 PM
Yes, you got me there. Thought I was still in the #javascript channel. My bad
👍 2