在Scala中表示值的约束的最佳方法?

时间:2010-12-20 15:38:26

标签: scala

表示Int字段或参数永远不应为负数的最佳表达方式是什么?

首先想到的是对类型的注释,例如case class Foo(x: Int @NotNegative)。但是我必须发明自己的注释,并且不会有任何编译时检查或任何东西。

有更好的方法吗?

3 个答案:

答案 0 :(得分:4)

为什么不使用单独的数据类型?

class Natural private (val value: Int) {
   require(value >= 0)

   def +(that:Natural) = new Natural(this.value + that.value)
   def *(that:Natural) = new Natural(this.value * that.value)
   def %(that:Natural) = new Natural(this.value % that.value)
   def |-|(that:Natural) = Natural.abs(this.value - that.value) //absolute difference

   override def toString = value.toString
}

object Natural {
  implicit def nat2int(n:Natural) = n.value
  def abs(n:Int) = new Natural(math.abs(n))
}

用法:

val a = Natural.abs(4711)
val b = Natural.abs(-42)
val c = a + b
val d = b - a  // works due to implicit conversion, but d is typed as Int
println(a < b) //works due implicit conversion

答案 1 :(得分:1)

稍微好一些(?),或许,但仍然没有编译器检查:require(x >= 0)

答案 2 :(得分:1)

Scala目前不支持合同和不变量。