試圖使用案例類實現智能構造函數。管理覆蓋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
也許這樣的事情是不可能的?