EY.Mohamed EY.Mohamed - 2 years ago 132
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)

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download