Scala Checking constructor / method parameters

I wanted to check out some of the best Scala programming practices since I am new to Scala. I read online about how Scala usually does not use exceptions, except for “exceptional” circumstances (which do not include parameter checking). Right now in my project I use a lot of require , so I wonder what would be the best way to type check.

For example, if I have a class

 class Foo(String bar){ require(StringUtils.isNotEmpty(bar), "bar can't be empty") } 

What are my alternatives to verifying? Create such a companion object

 Object Foo { def apply(bar: String) = Try[Foo] { bar match = { case null => Failure("can't be null") //rest of checks case _ => Success[Foo] } } 

Or should I use Option instead?

Also, for Scala methods, how can I check a method parameter? If I already return a parameter, am I just returning an empty parameter, if I get a bad parameter? Doesn’t this mean that I should check for an empty parameter when I use method return and do not throw an exception for a more specific message? (for example, runtime exception cannot use zeros).

+7
scala
source share
1 answer

I think part of the success of your companion object will also return a Foo () object?

  Object Foo { def apply(bar: String) = Try[Foo] { bar match = { case null => Failure("can't be null") //rest of checks case _ => Success[Foo](new Foo(bar)) } } 

To use it, you can do something with Success , which you will get from Foo (bar):

  val hehe = Foo(bar).map(foo => foo.someString()).getOrElse('failed') 

Try methods automatically throw exceptions thrown by someString () or whatever else you do inside it inside Failures. If you want to check the parameters of foo.someString() , you would do something similar to your apply() method. This is not so different from throwing exceptions, but I think it’s better because the “catch blocks” will be in recover() or recoverWith() . You can always exit Try with getOrElse() if your code was not designed for the Try chain from top to bottom.

+2
source share

All Articles