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

自闭症网瘾萝莉.ら 提交于 2019-11-27 21:47:39
missingfaktor

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

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 require that lets you write the same thing more concisely as follows:

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)

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.)
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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!