1

I wrote the following Scala 3 example to test the new explicit nulls feature:

class NullFoo:
  var s: String = _
  override def toString: String = s"Foo:s=$s"

object NullFoo:
  def main(args: Array[String]): Unit =
    println(new NullFoo)

My sbt file looks like this:

name := "scala3-features"

version := "0.1"

scalaVersion := "3.0.2"

scalacOptions ++= Seq(
  "-Ysafe-init", // renamed from -Ycheck-init, still present in official docs!
  "-Yexplicit-nulls",
  "-Xfatal-warnings"
)

and the code just runs fine:

sbt run
[info] welcome to sbt 1.5.5 (Ubuntu Java 11.0.11)
[info] loading global plugins from /home/chris/.sbt/1.0/plugins
[info] loading project definition from /home/chris/prj/as24/scala3-features/project
[info] loading settings for project scala3-features from build.sbt ...
[info] set current project to scala3-features (in build file:/home/chris/prj/as24/scala3-features/)
[info] running NullFoo 
Foo:s=null

But I thought it shouldn't according to https://docs.scala-lang.org/scala3/reference/other-new-features/explicit-nulls.html. What am I doing wrong?

Chris W.
  • 2,266
  • 20
  • 40

1 Answers1

3

As the documentation page mentions, it's still a work in progress. If you try your example replacing var s: String = _ with var s: String = null you get the compiler warning which you expect.

[error] -- [E007] Type Mismatch Error: Main.scala:2:18 
[error] 2 |  var s: String = null
[error]   |                  ^^^^
[error]   |                  Found:    Null
[error]   |                  Required: String
[error] one error found
Jarrod Baker
  • 1,150
  • 8
  • 13