如何检查构造函数参数并抛出异常或在 Scala 的默认构造函数中进行断言?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9169691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 03:52:14  来源:igfitidea点击:

How to check constructor arguments and throw an exception or make an assertion in a default constructor in Scala?

scalaexceptionconstructorassert

提问by Ivan

I would like to check constructor arguments and refuse to construct throwing IllegalArgumentExceptionin case the arguments set is not valid (the values don't fit in expected constraints). How to code this in Scala?

我想检查构造函数参数并拒绝构造抛出IllegalArgumentException,以防参数集无效(值不符合预期的约束)。如何在 Scala 中编码?

回答by missingfaktor

In Scala, the whole body of the class is your primary constructor, so you can add your validation logic there.

在 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 provides a utility method requirethat lets you write the same thing more concisely as follows:

Scala 提供了一种实用方法require,可以让您更简洁地编写相同的内容,如下所示:

class Foo(val i: Int) {
  require(i >= 0, "the number must be non-negative.")
}

A better approach might be to provide a factory method that gives a scalaz.Validation[String, Foo]instead of throwing an exception. (Note: requires Scalaz)

更好的方法可能是提供一个工厂方法,该方法给出一个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.)

回答by Luigi Plinge

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