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:
You can use a marker trait on primitve types in the following way
trait Positive
type PosInt = Int with Positive
def makePositive(i: Int): Option[PosInt] = if(i < 0) None else Some(i.asInstanceOf[PosInt])
def succ(i: PosInt): PosInt = (i + 1).asInstanceOf[PosInt]
But you will only get a runtime error for writing makePositive(-5)
. You will get a compile time error for writing succ(5)
.
It is probably possible to write a compiler plugin that "lifts" positive integer literals to a marked type.
I have not tested whether there is any runtime overhead for marking primitive types in such a way.