Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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()
- )
- }
Add Comment
Please, Sign In to add comment