1
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?

1 Answer 1

5

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) 
Sign up to request clarification or add additional context in comments.

7 Comments

Interesting. According to docs.scala-lang.org/overviews/collections/… this is the case. Sadly, I was depending on the behavior of either null converting to null, or failing to convert and immediately throwing an exception, which would result in a Failure. Now it looks like I will have to explicitly check for null, as opposed to using a Try.
@Leumash Why not work with an Option[List[String]] instead?
Because Option[List[String]] would behave in the same way as Try. Option(line.asJava).isDefined == true. I ended up matching line to case null => null and case _ => line.asJava.
But then the Option[T] would be None, not null, and you won't be depending on NullReferenceException, as you wouldn't need a Try[T] at all. You'd only need line.map { x => // stuff }.
Sorry, I edited my previous comment, I meant Option(line.asJava) is a Some.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.