Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Marking primitive types with phantom types in Scala

In Scala I can use the concept of phantom types (as described e.g. here) to mark types and have this information erased at runtime. I wonder whether it is possible to mark primitive types with phantom types without having them boxed.

An example could be a function that lets an Int only pass if it is a prime. The signature might look similar to the following:

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

The function returns the value Some(i) if i is prime or None else.

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

like image 640
ziggystar Avatar asked Jun 15 '11 13:06

ziggystar


1 Answers

The following works for me:

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 */
like image 126
Ken Bloom Avatar answered Sep 19 '22 06:09

Ken Bloom