gpt4 book ai didi

scala - 值类中的验证

转载 作者:行者123 更新时间:2023-12-02 08:24:53 24 4
gpt4 key购买 nike

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通过使用 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 - 值类中的验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33136558/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com