Union types

It’s not possible, you said it yourself.

There are a couple of alternative approaches. The best alternative approach depends on the particular case.

A very concise approach is using overloaded functions. For each of the types in the union create a separate overloaded function. These functions have the same name but different argument types. If the implementation of these functions has common logic, extract it to a private function that can be re-used by all of them. This approach might not work that well, depending on the nature of the common logic.

Another approach is what I call the typeclass approach. There is a proposal to add native support for typeclasses to Kotlin. It would reduce the boilerplate of using this approach. Without native support it has some boilerplate:

  1. For 2 independent types A and B create an interface I with 2 implementations IA(A) and IB(B).

  2. Instead of the union type use this interface as the type of the function argument.

  3. Give the interface all the members that you need in your function.

  4. For invocation convenience, create overloaded functions for A and B that delegate to the first function.

1 Like