scala Scala案例类:如何验证构造函数的参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20478588/
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
Scala case class: how to validate constructor's parameters
提问by j3d
Here below is a case classthat verifies the nameparameter is neither nullnor empty:
下面是一个案例类,用于验证name参数既非null空也非空:
case class MyClass(name: String) {
require(Option(name).map(!_.isEmpty) == Option(true), "name is null or empty")
}
As expected, passing nullor an empty string to nameresults in an IllegalArgumentException.
正如预期的那样,传递null或一个空字符串name中的结果IllegalArgumentException。
Is it possible to rewrite the validation to get either Successor Failureinstead of throwing an IllegalArgumentException
是否可以重写验证以获取Success或Failure代替抛出IllegalArgumentException
回答by vptheron
You can't have a constructor return something else than the class type. You can, however, define a function on the companion object to do just that:
您不能让构造函数返回类类型以外的其他内容。但是,您可以在伴随对象上定义一个函数来做到这一点:
case class MyClass private(name: String)
object MyClass {
def fromName(name: String): Option[MyClass] = {
if(name == null || name.isEmpty)
None
else
Some(new MyClass(name))
}
You can of course return a Validation, an Eitheror a Tryif you prefer.
如果您愿意Validation,您当然可以返回 a 、 anEither或 a Try。

