Hey. Kotlin doesn’t have union types, right? I can...
# arrow
a
Hey. Kotlin doesn’t have union types, right? I can’t take do this, right?
Copy code
val v1: Validator<E1>
val v2: Validator<E2>

listOf(v1, v2): List<Validator<E1 | E2>>
a
no, union types are not supported in Kotlin
j
I dream of a day we had union types in kotlin. I know what was said at KotlinConf but it would be amazing. I do really look forward to error types.
a
What was said at KotlinConf?
j

https://youtu.be/tAGJ5zJXJ7w?si=TKD-esW-SIEEf80_&amp;t=1552

TLDW: Limited support for union types for error types only
a
He mentioned "because union types are undecidable for compiler", any idea what is he referring to?
j
To be honest, I never understood their rationale for why they cannot add union types. That doesn't mean they dont have a good reason, I just dont know. Seems odd that this could be done for errors but not more generally but I am sure they have thought about it more than I have 🤷
a
adding general types like
String | Int
brings a lots of complications. One of the main problems is that it makes type checking blow up in terms of complexity, because to check something like "`A | B` is a subtype of `C | D`", you would need to check whether "`A` is a subtype of
C
and
B
is a subtype of `D`", or "`A` is a subtype of
D
and
B
is a subtype of
C
". A few steps later and you have a very large amount of constraints to check... which heavily impact the compiler and the IDE response times. There are also a few other technical complications, like what is the type of that value in the JVM. Think of something like
String | Int
. Is it a
Comparable<*>
? is it an
Object
(and then we need to box the int)? This feels more surmountable, but still complicated. The problem becomes much easier if you only admit types of the form
<Normal Type> | <Error>
where
<Error>
is a special kind of type with a few restrictions imposed on those. There will be a talk about how all of this looks at next KotlinConf https://kotlinconf.com/schedule/?day=2025-05-22&amp;session=a35f03c7-3d57-5874-a20e-8d7518ded091
👍 2
j
Thanks for the explanation. Its interesting for sure. I think some part of me just wants unwrapping of sealed interfaces when they conform to some pattern. Though to be honest when I want a union type its usually for errors. I'm excited to watch the talk!
a
On Scala
String | Int
becomes
Object
, I think that is a reasonable tradeoff.
all of these considerations still apply to the error unions as well, I don’t see how they are any different
I found a talk about union types

https://youtu.be/3uNpmhHwkuQ?si=nq7hj1dfy1N_J1vi&amp;t=1188