试图使用案例类实现智能构造函数。管理覆盖copy
法测得的,而且我相信在应该做的伎俩伴侣对象apply
,而是试图在BigInt
传递时,我碰了壁。我试图把在def apply(value: BigInt): Option[Natural]
但随后scalac
抱怨冲突的符号。斯卡拉智能构造函数的case类实现?
import spire.math.Integral // companion object contains implicit Integral[BigInt]
case class Natural private (value: BigInt) {
def copy(value: BigInt = this.value): Option[Natural] =
Natural.apply(value)
}
object Natural {
def apply[A](x: A)(implicit A: Integral[A]): Option[Natural] =
if (A.isPositive(x)) Some(Natural(x))
else None
}
/** In Foo.scala */
Natural(5L) // Option[Natural] = Some(Natural(5))
Natural(BigInt(5L)) // constructor Natural in class Natural cannot be accessed in object Foo
也许这样的事情是不可能的?