Leumash
Leumash

Reputation: 43

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?

Upvotes: 1

Views: 377

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149646

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)

Upvotes: 5

Related Questions