1

I'm going through Scala book.

Here is example:

  def toInt(s: String): Option[Int] = {
    try {
      Some(Integer.parseInt(s.trim))
    } catch {
      case e: Exception => None
    }
  }

  val x = null
  println(toInt(x)) // < ---- why compiler does not complain about Null ?

toInt should allow only String as an argument, but compiler is ok with null.

Why ? Such kind of behavior is disallowed in Rust and TypeScript.

Is there any flag or smth ?

3
  • 2
    Yep, Kotlin got this one right too. For all of the many, many things Scala did a wonderful job of, leaving null unchecked is very possibly the worst decision in Scala. It looks like Dotty may have something to say about it, for what it's worth Commented May 9, 2021 at 21:40
  • 2
    @SilvioMayolo Kotlin at least attempted to get it right, but soon enough found out that it's easier said than done; I didn't check on whether there have been any recent changes in that direction, though. Commented May 9, 2021 at 23:09
  • Maybe it's also worth explaining why it's different in TS and Rust. 1. TS had JS as foundation, and JS had no type system whatsoever. Therefore, TS's type system was basically a green-field project, and it had the opportunity to "do it right" from the beginning (which it did, quite successfully). This was not the case with Java, which already had String that included null etc. 2. Similarly for Rust: is had not to be compatible with any toxic legacy type annotations, so it did the right thing, and eliminated null as concept altogether. Commented May 10, 2021 at 17:03

1 Answer 1

3

Option can help because Option(null) == None

def toInt(s: String): Option[Int] =
  Option(s).flatMap(_.toIntOption)

toInt(null) // None

but usually we anticipate it with signatures like

def toInt(s: Option[String]): Option[Int]

and wrap legacy APIs that can return null with a Scala layer

toInt(Option(legacyJavaApi()))

Also linters like Wartremover could help: https://www.wartremover.org/doc/warts.html#null

Occasionally an initialisation trick with var x: A = null.asInstanceOf[A] is useful where A is a type parameter because otherwise what would you assign to x?.

Sign up to request clarification or add additional context in comments.

2 Comments

Is null some kind of super type for all types?
@captain-yossarian It is a subtype of every other reference type. Starting Scala 3 it can be changed so that it is only a subtype of Any with -Yexplicit-nulls flag.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.