1

I am new to Scala. I have a class that takes parameters as follows:

class myClass(val param: Params, val normalizer: Int){..

I have an apply method that initializes the class with default parameter values:

 def apply(): myClass = new myClass(AnotherClass.getParams, 1000) 

I want to restrict the normalizer parameter to allow construction of the object only if normalizer > 0, and throw an exception otherwise. However this should happen in all cases, not just in the default case in the apply method. What is the correct way to handle this situation?

Thanks, in advance.

bzak
  • 483
  • 4
  • 14

1 Answers1

0

Just add require(normalizer > 0) in the class body and create a class hierarchy based on that class etc.

See more details in the thread: what to choose between require and assert in scala.

Small example:

class test(n: Int){
  require(n > 10)
}

And the related Predef documentation.

Community
  • 1
  • 1
Pavel
  • 1,519
  • 21
  • 29
  • can you be more specific. does this go anywhere in the class definition? In this case what is the behavior if normalizer< 0? – bzak Dec 05 '16 at 15:21
  • Update answer with example! – Pavel Dec 05 '16 at 15:22
  • You will have to select link manually and put it in the browser. Its really works! just add extra: "f$.html" in the url. For some reason its not fully highlighted – Pavel Dec 05 '16 at 15:30