我想我明白斯卡拉2.10,新“值类”功能,通过与Haskell的比较newtype
:
trait BoundedValue[+This] extends Any { this: This =>
def upperBound: This
def lowerBound: This
}
class Probability @throws(classOf[IllegalArgumentException]) (v: Double) extends AnyVal with BoundedValue[Probability] {
val value: Double = if ((v >= 0.0) && (v <= 1.0)) v else throw new IllegalArgumentException((v.toString) + "is not within the range [0.0, 1.0]")
override val upperBound: Probability = new Probability(0.0)
override val lowerBound: Probability = new Probability(1.0)
// Implement probability arithmetic here;
// will be represented by Double at runtime.
}
这个问题我有是,如何值类出现的Java代码使用在其声明Scala的包? 是否值类表现为从Java侧引用类,或者是它完全擦除(并因此表现为它包装的类型)? 换句话说,怎样类型安全的值类的Java时所涉及的源代码级?
编辑
上面的代码不会编译,根据SIP-15文件(丹尼尔的回答联的),因为值类不允许有任何初始化逻辑,因为无论v
必须是明确地一个或VAL Probability
必须具有unbox
方法和相应的box
就可以了方法的同伴对象,因为值类必须有一个确切的领域。 正确的代码:
trait BoundedValue[This <: BoundedValue[This]] extends Any { this: This =>
def upperBound: This
def lowerBound: This
}
class Probability private[Probability] (value: Double) extends AnyVal with BoundedValue[Probability] {
@inline override def upperBound: Probability = new Probability(0.0)
@inline override def lowerBound: Probability = new Probability(1.0)
@inline def unbox: Double = value
// Implement probability arithmetic here;
// will be represented by Double at runtime (mostly).
}
object Probability {
@throws(classOf[IllegalArgumentException])
def box(v: Double): Probability = if ((v >= 0.0) && (v <= 1.0)) new Probability(v) else throw new IllegalArgumentException((v.toString) + "is not within the range [0.0, 1.0]")
}
这个问题本身仍然是有效的,然而。