scalavalue-class

Scala Prohibit allocation of value classes


According to the documentation on value classes, they may be allocated under a number of circumstances:

Allocation Summary

a value class is treated as another type.

a value class is assigned to an array.

doing runtime type tests, such as pattern matching.

Is there anyway to say,throw a compilation error if these circumstances occur?


Solution

  • There is nothing built-in (AFAIK).

    You could write an SBT plugin which inspects the .class files after compile task finishes (using a library like BCEL, ASM, etc.) and fails if it finds any value class constructor calls.

    Alternately, you should be able to do the same with a compiler plugin (unfortunately, documentation I was able to find is quite old) with a little more difficulty.