Union types: They can be introduces in a limited,...
# language-proposals
l
Union types: They can be introduces in a limited, yet useful way: In the only place where we also have intersection types, which is the
where
clause that specifies type arguments constraints for a function. I think that would satisfy many use cases where we currently write multiple functions (often extensions). The
when
expression would also need to be tweaked to make use of this I think, and probably some compiler magic, and maybe
@JvmOverloads
, unless these functions are required to have the union type constrained generic argument to be
reified
, which requires the function to be
inline
, and always inlining the code.
1
i
Copy code
inline fun <reified T> T.printIntOrString() where T : Int or String = when (this) {
  is Int -> print("int! $this")
  is String -> print ("string. $this")
}
yes black 2
🤔
a
to Union Types, though I'm interested in seeing the proposed syntax for declaring a union type. In Typescript declaring a union type is trivial, and it's really nice. In Kotlin you can effectively mimic them with sealed classes, but it takes a lot more boilerplate.
j
The syntax is the least interesting part of union types though. The underlying implementation on the JVM, JS, and native, and how those are exposed to Java, JS, and C is far more interesting and challenging to get right.
l
If it only works for reified type parameters (as suggested in this proposal), interop is out of the question since it's a Kotlin only feature that only applies to inlined code.
a
I miss algebraic data types so much 😢
l
@Astronaut4449 Kotlin has a version of them in the form of `sealed class`es.
a
I know, but that's sometimes just not enough.