Search code examples
scalatypes

Is it possible to restrict Int by creating something like PositiveInt and have compile-time checks in Scala?


Is it possible to create a restricted Int such as PositiveInt and have compile-time checks for it? In other words is it possible to define a method such as:

def myMethod(x: PositiveInt) = x + 1

and then have something like:

myMethod(-5) // does not compile
myMethod(0)  // does not compile
myMethod(5)  // compiles

If this is possible how should I start with defining PositiveInt, I mean is there a convenient technique for this in Scala?


Solution

  • This kind of thing is called dependent typing, and no, it's not available in Scala.