Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to express union types in Kotlin?

Union types, also known as sum types are a powerful language feature that I find myself using often in TypeScript

something along the lines of:

let a: string | number = “hello”
a = 3

How would I achieve this type of behavior in kotlin?

I saw some people talking about using inheritance and sealed classes to accomplish this but it looks like if you want to use that approach with primitives (such as String and Int) then one would have to write wrappers around those types to access the underlying value.

Im wondering if there is a more pragmatic solution.

like image 992
Ben Kosten Avatar asked Dec 03 '25 22:12

Ben Kosten


2 Answers

There is an issue in Kotlin issue tracker: Denotable union and intersection types (it also contains links to a few previous discussions). The last update from the team is

Roman Elizarov commented 19 Nov 2021 18:14
Short update on this issue. This is an interesting and important feature, but it is really hard to integrate into the language in a backward-compatible and pragmatic way. We'll start working on it fully when we release the new K2 compiler and the best compiler engineers from our team will be able to start looking into it.

like image 174
Alexey Romanov Avatar answered Dec 06 '25 15:12

Alexey Romanov


As far as I know, there isn't really a "pretty" way to do it in kotlin One way to achieve a variable that can hold strings and ints could look like that:

var x: Any = 5
x = "hello"

but as you can notice, X can hold any type not only strings and ints, but you could use the "Either" class, from Arrow library (If I'm not mistaken) which allows such behaviour:

var x = Either<Int, String>(5)

Either way, I'm not really sure why would you need such a variable

like image 28
JustSightseeing Avatar answered Dec 06 '25 17:12

JustSightseeing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!