How to express union types in Kotlin?

Ben Kosten

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.

JustSightseeing

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related