> is there built-in support for polymorphic arr...
# announcements
p
is there built-in support for polymorphic arrays, and sealed classes?
s
What do you mean by “polymorphic arrays”? Things like List<Int> are resolved and serialized statically. List<Any> and List<*> requires polymorphism, though. Now it is supported only in Jackson-style - object becomes an array of type and object. Same for class hierarchies. We plan to add static support for sealed classes, but not now.
p
I meant class hierarchies, yes. I’ve seen many backends modeled straight from the OOP playbook of Cat inherits from Mammal, which inherits from Animal, so the endpoint returns, as per the documentation, “an array of Animal that can contain any kind of Bird, Whales, or one Kangaroo. If JS can deserialize it so can Java. Good luck!”
It can be done with Jackson for sure with some optional dependency. It can be done, just worse, on Gson because I wrote fixes for the implementation and they got rejected upstream 😞
s
This thing is rather limited for now. All you can have is:
Copy code
@Serializable
open class A() {
    val a: Int = 42
}

@Serializable
class B: A() {
    val b: String = "42"
}

@Serializable
class Box(val a: A)

fun main(args: Array<String>) {
    val s = JSON.stringify(Box(B()))
    val b = JSON.parse<Box>(s)
    println(s)
    println(b.a is B)
}
will produce
{"a":["B",{"a":42,"b":"42"}]}
, and
true
p
I see
wait where do the [ ] come from?
s
It’s similar to Jackson’s WRAPPER_ARRAY setting
p
I don’t remember what it does. Does it wrap objects in arrays where arr[0] is their typename?
s
yep, as you can see
arr[1] is then the object itself
p
yep
okay then polymorphic arrays can be supported
val b = JSON.parse<List<Animal>>(/*..*/)
the types are already annotated
if I hint it with generics
you should be able to match it with the nearest common ancestor I guess
reified generics?
s
in this case, they will be statically deserialized as Animals
ah, no
if Animal is open class, array of object and type would be expected in each element
p
awww
val b = JSON.parse<List<List<Any>>>(…)
what happens with the missing information?
dropped?
it should be at least typed to
Tuple<String, Map<String, Any>>
to avoid info loss
scary stuff xD
s
in List<List<*>> first type argument(List) is static, so there’s no surprises 🙂
p
👍🏽
thank you for your time
I guess it’s late there too
s
yep, I’m now going to sleep
no problem