Advertisement
Hauber

Pattern for Union of Value Types

Nov 2nd, 2024 (edited)
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 0.52 KB | Source Code | 0 0
  1. class T private constructor(private val value: Value) {
  2.     sealed class Value {
  3.         data class IntValue(val int: Int) : Value()
  4.         data class BoolValue(val bool: Boolean) : Value()
  5.     }
  6.  
  7.     companion object {
  8.         fun fromInt(int: Int): T = T(Value.IntValue(int))
  9.         fun fromBoolean(bool: Boolean): T = T(Value.BoolValue(bool))
  10.     }
  11.  
  12.     override fun toString(): String = when (value) {
  13.         is Value.IntValue -> value.int.toString()
  14.         is Value.BoolValue -> value.bool.toString()
  15.     }
  16. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement