If I wanted to define a Map where the value is som...
# getting-started
s
If I wanted to define a Map where the value is some finite set of types, is there any way to properly type that union? My recollection of several years ago is that there was no way to properly define union types in Kotlin, just wondering if that’s changed?
a
it depends on what exactly you want, but there are
sealed class
and
sealed interface
which fulfil a similar purpose. https://kotlinlang.org/docs/sealed-classes.html Of course this requires you can add an interface to all the types. If the types aren’t under you control, you could consider packaging them in a value class. union & intersection types should be coming one day… https://youtrack.jetbrains.com/issue/KT-13108/Denotable-union-and-intersection-types
s
It’s unfortunate because intersections are already supported with the where clause I think.
p
not for “any arbitrary union type”, and JVM only, but EnumMaps are more efficient and a bit cleaner conceptually (if you can in fact use an enum to represent your keys): https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/EnumMap.html