Do not call get on an Try

When retrieving the content of a Try, do not use get.


Some Trys are Failures, and get deals with them by throwing an exception.

scala.util.Failure(new Exception).get
// java.lang.Exception
// 	at repl.Session$App$$anonfun$1.apply(
// 	at repl.Session$App$$anonfun$1.apply(

If you have a default value to provide in case of a Failure, use getOrElse:

scala.util.Failure(new Exception).getOrElse(-1)
// res0: Int = -1

Another practical approach is to use fold, which lets you provide a handler for each case:

import scala.util.{Failure, Try}

(Failure(new Exception): Try[Int]).fold(
  e => s"Found an error: '${e.getMessage}'",
  i => s"Found an int: '$i'"
// res1: String = "Found an error: 'null'"

Checked by

  • TryGet