SIP-15意味着可以使用值类来定义例如新的数字类,例如正数。是否有可能在没有构造函数的情况下编写这样的约束,即底层> 0,而无需调用单独的方法来验证约束(即;创建这样一个类的有效实例是简单的)?
如果值类有构造函数的概念,那么它可以有一个地方有这样的验证,如下面,但这是不支持的(即;下面的代码将无法编译)
implicit class Volatility(val underlying: Double) extends AnyVal {
require(!underlying.isNaN && !underlying.isInfinite && underlying > 0, "volatility must be a positive finite number")
override def toString = s"Volatility($underlying)"
}
Volatility(-1.0) //should ideally fail
您可以使用refined的Positive
谓词来细化您的Double
,从而将验证步骤提升到编译时间:
import eu.timepit.refined.auto._
import eu.timepit.refined.numeric._
import shapeless.tag.@@
scala> implicit class Volatility(val underlying: Double @@ Positive) extends AnyVal
defined class Volatility
scala> Volatility(1.5)
res1: Volatility = Volatility@3ff80000
scala> Volatility(-1.5)
<console>:52: error: Predicate failed: (-1.5 > 0).
Volatility(-1.5)
^
向标记为已通过运行时要求的类型的隐式转换。
scala> trait Pos
defined trait Pos
scala> implicit class P(val i: Int with Pos) extends AnyVal { def f = i }
defined class P
scala> implicit def cv(i: Int): Int with Pos = { require(i>0); i.asInstanceOf[Int with Pos] }
warning: there was one feature warning; re-run with -feature for details
cv: (i: Int)Int with Pos
scala> new P(42).f
res0: Int with Pos = 42
scala> :javap -prv -
17: invokevirtual #35 // Method $line5/$read$$iw$$iw$.cv:(I)I
20: invokevirtual #38 // Method $line4/$read$$iw$$iw$P$.f$extension:(I)I
scala> new P(-42).f
java.lang.IllegalArgumentException: requirement failed
at scala.Predef$.require(Predef.scala:207)
at .cv(<console>:13)
... 33 elided
你也可以使用私有方法来执行不变量。
scala> implicit class P(val i: Int with Pos) extends AnyVal { private def g = require(i>0) ; def f = { g; i } }
defined class P
scala> new P(-42.asInstanceOf[Int with Pos]).f
java.lang.IllegalArgumentException: requirement failed
at scala.Predef$.require(Predef.scala:207)
at P$.$line10$$read$P$$g$extension(<console>:14)
at P$.f$extension(<console>)
... 33 elided
我完成这一任务的方法是在调用case类的private
构造函数"实例化"该值之前,使用同伴对象的.apply
方法添加require
约束。
警告:下面的代码将无法在REPL/Scala工作表中编译。扩展AnyVal的case类必须是顶级类;也就是说,不能嵌套在另一个类、trait或对象的作用域中。REPL和Scala工作表都是通过在执行之前将所有代码推入一个不可见的包含类来实现的。
object PositiveInt {
def apply(value: Int): PositiveInt = {
require(value >= 0, s"value [$value] must be greater than or equal to 0")
new PositiveInt(value)
}
}
case class PositiveInt private(value: Int) extends AnyVal
val positiveTestA = PositiveInt(0)
val positiveTestB = PositiveInt(1)
val positiveTestC = PositiveInt(-1) //throws required exception
这是否适用于您的用例?将构造函数设为私有,并使用带有验证逻辑的伴侣对象来创建新实例。
class User private (val userIdentifier:String) extends AnyVal {}
object User {
def apply(userIdentifier: String): User = {
if(Option(userIdentifier).exists(_.trim.isEmpty)) throw new IllegalArgumentException("User identifier cannot be empty!")
new User(userIdentifier)
}
}