Created
January 22, 2019 16:54
-
-
Save westonal/33ce503cd6fce65a9d64fb11ed5032cc to your computer and use it in GitHub Desktop.
Union idea
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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