Pattern for Union of Value Types
class T private constructor(private val value: Value) {
sealed class Value {
data class IntValue(val int: Int) : Value()
data class BoolValue(val bool: Boolean) : Value()
}
companion object {
fun fromInt(int: Int): T = T(Value.IntValue(int))
fun fromBoolean(bool: Boolean): T = T(Value.BoolValue(bool))
}
override fun toString(): String = when (value) {
is Value.IntValue -> value.int.toString()
is Value.BoolValue -> value.bool.toString()
}
}
Comments
0 B
|👍
/👎
0 B
|👍
/👎
0 B
|👍
/👎