Can anyone explain this?

I know it’s Friday, so perhaps my neurons are misfiring, but I’ve gazed at this for a few minutes, and I just can’t figure out how it’s possible.

Welcome to Scala 2.12.4 (OpenJDK 64-Bit Server VM, Java 1.8.0_191).
Type in expressions for evaluation. Or try :help.

scala> import

scala> Option(AlgorithmParameters.getInstance("AES"))
res0: Option[] = Some(null)
1 Like

It’s not that magical

public final String toString()
Returns a formatted string describing the parameters.
toString in class Object
a formatted string describing the parameters, or null if this parameter object has not been initialized.

Wow, that’s pretty crazy, toString() returning null?!?

Good find, thanks!

Yep. Imperative programming at its finest. It even trips the REPL:

  at scala.runtime.ScalaRunTime$.replStringOf(ScalaRunTime.scala:268)
  at .$print$lzycompute(<console>:9)
  at .$print(<console>:6)
  at $print(<console>)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(
  at java.lang.reflect.Method.invoke(

The code where NPE is thrown:

  /** stringOf formatted for use in a repl result. */
  def replStringOf(arg: Any, maxElements: Int): String = {
    // here s is null, because arg.toString is null
    val s  = stringOf(arg, maxElements)
    val nl = if (s contains "\n") "\n" else ""

    nl + s + "\n"
1 Like

This is a great puzzler.

Thanks to Som Snytt, the 2.13 REPL does a better job:

scala 2.13.0-RC3> class C { override def toString = null }
defined class C

scala 2.13.0-RC3> Option(new C)
res1: Option[C] = Some(null)

scala 2.13.0-RC3> new C
res2: C = null toString

see with bonus tpolecat!