https://kotlinlang.org logo
#announcements
Title
# announcements
p

pakoito

09/28/2017, 12:00 AM
is there built-in support for polymorphic arrays, and sealed classes?
s

sandwwraith

09/28/2017, 12:03 AM
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

pakoito

09/28/2017, 12:08 AM
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

sandwwraith

09/28/2017, 12:15 AM
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

pakoito

09/28/2017, 12:16 AM
I see
wait where do the [ ] come from?
s

sandwwraith

09/28/2017, 12:21 AM
It’s similar to Jackson’s WRAPPER_ARRAY setting
p

pakoito

09/28/2017, 12:22 AM
I don’t remember what it does. Does it wrap objects in arrays where arr[0] is their typename?
s

sandwwraith

09/28/2017, 12:23 AM
yep, as you can see
arr[1] is then the object itself
p

pakoito

09/28/2017, 12:24 AM
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

sandwwraith

09/28/2017, 12:28 AM
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

pakoito

09/28/2017, 12:30 AM
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

sandwwraith

09/28/2017, 12:35 AM
in List<List<*>> first type argument(List) is static, so there’s no surprises 🙂
p

pakoito

09/28/2017, 12:38 AM
👍🏽
thank you for your time
I guess it’s late there too
s

sandwwraith

09/28/2017, 12:39 AM
yep, I’m now going to sleep
no problem
2 Views