我编写了下面的Scala 3示例来测试新的显式null特性:
class NullFoo:
var s: String = _
override def toString: String = s"Foo:s=$s"
object NullFoo:
def main(args: Array[String]): Unit =
println(new NullFoo)
我的sbt文件看起来像这样:
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"
)
和代码运行正常:
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
但我认为它不应该根据https://docs.scala-lang.org/scala3/reference/other-new-features/explicit-nulls.html。我做错了什么?
正如文档页面所提到的,这项工作仍在进行中。如果你尝试用var s: String = null
替换var s: String = _
,你会得到你期望的编译器警告。
[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