Guest User

Untitled

a guest
Jan 23rd, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.88 KB | None | 0 0
  1. interface A {
  2. fun getInt(): Int
  3. }
  4.  
  5. interface B {
  6. fun getString(): String
  7. }
  8.  
  9. sealed class Union<TA, TB> {
  10. class Left<T1, T2>(val value: T1) : Union<T1, T2>()
  11. class Right<T1, T2>(val value: T2) : Union<T1, T2>()
  12. }
  13.  
  14. fun A.union(): Union<A, B> {
  15. return Union.Left(this)
  16. }
  17.  
  18. fun B.union(): Union<A, B> {
  19. return Union.Right(this)
  20. }
  21.  
  22. fun kotlinTypeUnion(param: Union<A, B>) {
  23. println(
  24. when (param) {
  25. is Union.Left -> param.value.getInt() // .value is an A
  26. is Union.Right -> param.value.getString() // .value is a B
  27. }
  28. )
  29. }
  30.  
  31. fun main() {
  32.  
  33. kotlinTypeUnion(
  34. object : A {
  35. override fun getInt(): Int {
  36. return 123
  37. }
  38. }.union()
  39. )
  40.  
  41. kotlinTypeUnion(
  42. object : B {
  43. override fun getString(): String {
  44. return "str"
  45. }
  46. }.union()
  47. )
  48. }
Add Comment
Please, Sign In to add comment