Leumash Leumash - 3 months ago 11
Scala Question

Scala Try - Should this not result in a Failure?

import scala.collection.JavaConverters._

val line: List[String] = null
val myTry = Try(line.asJava)

val result = myTry match {
case Success(_) => "Success"
case Failure(_) => "Failure"
}

println(result)


This code snippet prints "Success". If I try to access
myTry.get
, then it throws a
NullPointerException
.

From how I understand Try, shouldn't myTry be a Failure?

Answer

From how I understand Try, shouldn't myTry be a Failure?

Specifically, asJava on a List creates a wrapper around the original collection in the form of a SeqWrapper. It doesn't iterate the original collection:

case class SeqWrapper[A](underlying: Seq[A]) extends ju.AbstractList[A] with IterableWrapperTrait[A] {
    def get(i: Int) = underlying(i)
}

If you use anything else that does iterate the collection or tries to access it, like toSeq, you'll see the failure:

import scala.collection.JavaConverters._

val line: List[String] = null
val myTry = Try(line.toSeq)

val result = myTry match {
  case Success(_) => "Success"
  case Failure(_) => "Failure"
}

println(result)