EY.Mohamed EY.Mohamed - 10 months ago 85
Scala Question

If statement in value class

i need to validate the parameter of my value class (below) . But i get an error

this statement is not allowed in value class

at compile time , is there a way around this ? Thanks.

case class Size(val size: Long) extends AnyVal {
if (size < 0) throw new IllegalArgumentException; // error
def +(s: Size): Size =Size(size + s.size)


Value class is a wrapper around an existing object, so Scala doesn't in fact instantiate value class object, but use underlying object instead (that's why SIP-15 exists in the first place). Hence there is no place to put initialization code and runtime check of size is simply not possible.