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 java.security._
import java.security._

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

It’s not that magical https://docs.oracle.com/javase/8/docs/api/java/security/AlgorithmParameters.html#toString--

public final String toString()
Returns a formatted string describing the parameters.
Overrides:
toString in class Object
Returns:
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:

scala> java.security.AlgorithmParameters.getInstance("AES")
java.lang.NullPointerException
  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(NativeMethodAccessorImpl.java:62)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:498)
  at scala.tools.nsc.interpreter.IMain$ReadEvalPrint.call(IMain.scala:742)

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 https://github.com/scala/scala/pull/6706. with bonus tpolecat!