Best way to represent value constraints in Scala?

What is the best way to express that, say, an Int field or parameter should never be negative?

The first thing that comes to mind is the annotation for the type, for example case class Foo(x: Int @NotNegative) . But I would have to come up with my own annotation, and there would be no compilation time check or anything else.

Is there a better way?

+4
source share
3 answers

Why not use a separate data type?

 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)) } 

Using:

 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 
+4
source

A little better (?), Perhaps, but not yet checking the compiler: require(x >= 0) .

+1
source

Contracts and invariants are not currently supported by Scala.

+1
source

Source: https://habr.com/ru/post/1332783/


All Articles