https://kotlinlang.org logo
#getting-started
Title
# getting-started
s

Sam Garfinkel

03/17/2023, 1:21 AM
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

Adam S

03/17/2023, 2:02 AM
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

Sam Garfinkel

03/17/2023, 3:11 AM
It’s unfortunate because intersections are already supported with the where clause I think.
p

Paul Griffith

03/17/2023, 5:11 AM
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
7 Views