2

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)
}
Pramod Gharu
  • 1,105
  • 3
  • 9
  • 18
EY.Mohamed
  • 82
  • 6
  • I guess your problem is `size` parameter. Because value class can't be parameter of another value of another value class. – Sergii Lagutin Aug 30 '16 at 12:19
  • http://docs.scala-lang.org/sips/completed/value-classes.html, namely the part "C may not have initialization statements." – Victor Moroz Aug 30 '16 at 12:41
  • 1
    Sèe this: http://stackoverflow.com/questions/33136558/validations-in-value-classes – Samar Aug 30 '16 at 13:04

1 Answers1

5

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.

Victor Moroz
  • 9,167
  • 1
  • 19
  • 23