如何检查构造函数参数并抛出异常或在Scala的默认构造函数中作出

如何检查构造函数参数并抛出异常或在Scala的默认构造函数中作出

本文介绍了如何检查构造函数参数并抛出异常或在Scala的默认构造函数中作出断言?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

在Scala中,类的全部是您的主要构造函数,因此可以添加您的验证逻辑。

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提供了一种实用方法 that让你更简洁地写下同样的事情,如下所示:

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.")
}

更好的方法可能是提供一种给出一个 scalaz.Validation [String,Foo] 而不是抛出异常的工厂方法。 (注意:需要Scalaz)

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的默认构造函数中作出断言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 19:59