How to express union types in Kotlin?

Viewed 350

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.

2 Answers

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

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.

Related