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:
Building on Kim Stebel's answer I've compiled the following
and invoked javap on the class
Test
with the following resultWe notice, that the function
testOddity
has been compiled to return an unboxed integer.And the following file doesn't compile (which is also what we wanted).
compiler error