Marking primitive types with phantom types in Scala

In Scala, I can use the phantom type concept (as described, for example here ) to mark types and delete this information at runtime. I wonder if primitive types can be marked with phantom types without inserting them.

An example would be a function that allows you to pass Int only if it is simple. A signature might look something like this:

def filterPrime(i: Int): Option[Int with IsPrime]

The function returns Some(i)if it iis simple or Noneelse.

Is the stated idea possible to implement in Scala without boxing a primitive integer?

+5
source share
2

:

trait IsPrime
val x = 5.asInstanceOf[Int with IsPrime]
val y:Int = x

val z:Int with IsPrime = 6 /* this line causes a compile error
                              which is what you want */
+5

,

trait IsOdd

object Test{
    def testOddity(i: Int): Int with IsOdd = 
        if( i % 2 == 0) throw new RuntimeException
        else i.asInstanceOf[Int with IsOdd]

    def main(args: Array[String]) {
        println(testOddity(1))
    }
}

javap Test :

Compiled from "Test.scala"
public final class Test extends java.lang.Object{
public static final void main(java.lang.String[]);
  Code:
   0:   getstatic   #11; //Field Test$.MODULE$:LTest$;
   3:   aload_0
   4:   invokevirtual   #13; //Method Test$.main:([Ljava/lang/String;)V
   7:   return

public static final int testOddity(int);
  Code:
   0:   getstatic   #11; //Field Test$.MODULE$:LTest$;
   3:   iload_0
   4:   invokevirtual   #17; //Method Test$.testOddity:(I)I
   7:   ireturn

}

, testOddity unboxed.

( , ).

trait IsOdd

object Test{
    def testOddity(i: Int): Int with IsOdd = 
        if( i % 2 == 0) throw new RuntimeException
        else i.asInstanceOf[Int with IsOdd]

    def acceptOdd(i: Int with IsOdd) { println("got it") }  
    def main(args: Array[String]) {
        println(testOddity(1))
        acceptOdd(1)
    }
}

Test.scala:11: error: type mismatch;
 found   : Int(1)
 required: Int with IsOdd
        acceptOdd(1)
                      ^
+4

All Articles