我想检查构造函数参数并拒绝构造throw IllegalArgumentException
,以防参数集无效(值不符合预期约束)。如何在Scala中编写代码?
答案 0 :(得分:85)
在Scala中,类的整个主体是您的主要构造函数,因此您可以在那里添加验证逻辑。
scala> class Foo(val i: Int) {
| if(i < 0)
| throw new IllegalArgumentException("the number must be non-negative.")
| }
defined class Foo
scala> new Foo(3)
res106: Foo = Foo@3bfdb2
scala> new Foo(-3)
java.lang.IllegalArgumentException: the number must be positive.
Scala提供了一种实用工具方法require
,可以让您更简洁地编写相同的内容,如下所示:
class Foo(val i: Int) {
require(i >= 0, "the number must be non-negative.")
}
更好的方法可能是提供一个工厂方法,该方法提供scalaz.Validation[String, Foo]
而不是抛出异常。 (注意:需要Scalaz)
scala> :paste
// Entering paste mode (ctrl-D to finish)
class Foo private(val i: Int)
object Foo {
def apply(i: Int) = {
if(i < 0)
failure("number must be non-negative.")
else
success(new Foo(i))
}
}
// Exiting paste mode, now interpreting.
defined class Foo
defined module Foo
scala> Foo(3)
res108: scalaz.Validation[java.lang.String,Foo] = Success(Foo@114b3d5)
scala> Foo(-3)
res109: scalaz.Validation[java.lang.String,Foo] = Failure(number must be non-negative.)
答案 1 :(得分:17)
scala> class Foo(arg: Int) {
| require (arg == 0)
| }
defined class Foo
scala> new Foo(0)
res24: Foo = Foo@61ecb73c
scala> new Foo(1)
java.lang.IllegalArgumentException: requirement failed