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

后端 未结 4 1187
失恋的感觉
失恋的感觉 2021-01-07 18:16

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:

4条回答
  •  长发绾君心
    2021-01-07 19:10

    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.

    Edit

    I have not tested whether there is any runtime overhead for marking primitive types in such a way.

提交回复
热议问题