Skip to content

Instantly share code, notes, and snippets.

@westonal
Created January 22, 2019 16:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save westonal/33ce503cd6fce65a9d64fb11ed5032cc to your computer and use it in GitHub Desktop.
Save westonal/33ce503cd6fce65a9d64fb11ed5032cc to your computer and use it in GitHub Desktop.
Union idea
interface A {
fun getInt(): Int
}
interface B {
fun getString(): String
}
sealed class Union<TA, TB> {
class Left<T1, T2>(val value: T1) : Union<T1, T2>()
class Right<T1, T2>(val value: T2) : Union<T1, T2>()
}
fun A.union(): Union<A, B> {
return Union.Left(this)
}
fun B.union(): Union<A, B> {
return Union.Right(this)
}
fun kotlinTypeUnion(param: Union<A, B>) {
println(
when (param) {
is Union.Left -> param.value.getInt() // .value is an A
is Union.Right -> param.value.getString() // .value is a B
}
)
}
fun main() {
kotlinTypeUnion(
object : A {
override fun getInt(): Int {
return 123
}
}.union()
)
kotlinTypeUnion(
object : B {
override fun getString(): String {
return "str"
}
}.union()
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment