Union types

I find a lot of these proposals to be unnecessarily verbose to both define and use in practice. I think an idiomatic approach to this that leans on existing kotlin principles could be a simple sealed typealias

sealed typealias FlexibleDate = String | Long | Instant

Basic principle is that the alias alone is just a bounded set of types, and you but then unwrap with a conventional when or instance check. That’s all Kotlin would be doing special here, and the rest continues on as normal kotlin code once the type is checked.

  • Keywords already exist. RHS expression syntax would need a little work but it could work
  • At runtime they’re all just objects getting casted, but there’s plenty of precedent for this (generics)
  • Self-contained in the alias expression
  • Doesn’t allow anonymous expressions like typescript or similar languages do, which I think is a net positive
  • Can be compiler-checked just like sealed classes but without requiring inheritance. Instance check just results in a smart cast like sealed classes or other instance checks do today
when (someDate) {
  is String -> println("Date is $someDate")
  is Number -> println(someDate - 3L)
  is Instant -> println("Date is ${someDate.epochMillis()}")
}
13 Likes