Do not call get on an Try

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

Reason

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(try_get.md:9)
// 	at repl.Session$App$$anonfun$1.apply(try_get.md:9)

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

LinterRule
Scapegoat
  • TryGet
WartRemover