Hauber icon

Pattern for Union of Value Types

Hauber | PRO | 11/02/24 01:22:23 PM UTC (Edited) | 0 ⭐ | 12264 👁️ | Never ⏰ | []
Kotlin |

520 B

|

Source Code

|

0 👍

/

0 👎

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

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎

    
        
  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎

    
        
  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎