3

Since the NotNull trait is being deprecated, what is the new best way to declare my classes not nullable?

There is still the compiler option (does not prevent someone from misusing my libraries in other projects). Along with the handful of conflicting Java annotations that I doubt the Scala compiler will respect.

user833970
  • 2,729
  • 3
  • 26
  • 41

1 Answers1

1

You should not be using null in Scala at all, and if you don't, it's not necessary to use the NotNull trait.

If you have values or variables which can have "no value", use the Option type instead of the null value. Option has two subclasses: Some and None.

// text is "None", which means it has no value
var text: Option[String] = None

// Use "Some" when it should have a value
text = Some("Hello World")

Option has lots of useful methods; it can (more or less) be treated as a collection that has zero or one elements, so you can call common collection methods on it and you can use it with pattern matching.

text match {
  case Some(s) => println("Text: " + s)
  case None    => println("Empty")
}
Jesper
  • 202,709
  • 46
  • 318
  • 350
  • 1
    I don't use null in Java either. I want to prevent other people from using null. – user833970 Feb 09 '14 at 22:51
  • Using `null` isn't idiomatic Scala, so in general Scala programmers will not use `null`. – Jesper Feb 09 '14 at 22:52
  • 6
    Creating bugs isn't idiomatic Scala either - but they still happen. – Mike Allen Jun 02 '14 at 12:12
  • Not using null at all is nice, but sometimes you need to interact with libraries that do, such as the Scala standard library. Regex example: "foo(.*r)?".r.unapplySeq("foo") == Some(List(null)) – aij Jul 01 '16 at 19:04
  • @aij That is strange behaviour, I would consider that a bug. Please consider [reporting it as a bug](http://scala-lang.org/contribute/bug-reporting-guide.html). – Jesper Jul 01 '16 at 20:32
  • @Jesper I'm assuming redesigning the API in a way that would break backwards compatibility falls outside the scope of a bug... There's a reason Scala supports null. – aij Jul 02 '16 at 23:16
  • @aij Scala mainly supports `null` for interoperability with Java. Prefer using `Option` (`Some` and `None`) instead of `null` in Scala code. – Jesper Jul 03 '16 at 07:27
  • `assert(x!=null)` here and there to be safe – Hartmut Pfarr Feb 26 '21 at 21:52