值类中的验证

2023-11-29

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通过改进您的代码来提升验证步骤以缩短编译时间Double与精致的Positive谓词:

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)
                   ^

请注意,最后一个错误是编译错误而不是运行时错误。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

值类中的验证 的相关文章

随机推荐