Suppose I wanted to declare in an method declaration somewhere that it could only take a string that was known not to be empty, and not incur any runtime cost for doing so. Something like:
class NonEmptyString(val s: String) extends AnyVal {}
object NonEmptyString {
def apply(s: String) {
require(!s.isEmpty)
new NonEmptyString(s)
}
}
Would seem to do the trick, but it would in theory allow someone to just new-up another one as required.
If it were not a value class, I could simply put the check in the constructor, but value classes aren't able to have constructors:
scala> class NonEmptyString(val s: String) extends AnyVal { require(!s.isEmpty) }
<console>:7: error: this statement is not allowed in value class
class NonEmptyString(val s: String) extends AnyVal { require(!s.isEmpty) }
There's a couple of places where this would be a useful technique in my current project, has anyone come up with a good way to add invariants to value classes?