Dmitry Nogin
Dmitry Nogin

Reputation: 3750

Automatic null assert in scala

I would like to use ! symbol to automatically generate non-null assert in Scala. I mean that in a situation like this:

class Person(val name:String) {
  assert(name != null)  
} 

all other integrity checks can be solved by having custom argument type, but null check is always required to be written again and again. Could I have just something like this?

class Person(val name:String!) // note the bang (!)

and have that assert be generated? Are there any simple macros?

Upvotes: 0

Views: 2132

Answers (1)

jwvh
jwvh

Reputation: 51271

You can get something sort of similar via an implicit class.

implicit class StringCheck(str :String) {
  def ! :String = {assert(str != null); str}
}

With this the null test syntax is reduced...

import scala.language.postfixOps
class Person(val name:String) {name!} 

...or perhaps inserted in other code.

class Person(val name:String) {
  if (name.!.length > 10) ...
  else ...  
} 

A more generalized version as suggested by @simpadjo.

implicit class NotNullSupport[T](val obj :T) extends AnyVal {
  def ! : T = {assert(obj != null); obj}
}

Upvotes: 1

Related Questions