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?
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 */
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With