, foreach, , @vptheron, :
implicit class EnhancedTry[T](t: Try[T]) {
def forfailed[U](f: Throwable => U): Unit = t match {
case Failure(e) => f(e)
case _ => ()
}
}
val t = Try {
throw new Exception("An error")
}
t.forfailed(e => println(e.getMessage))
t.forfailed {
case e : NullPointerException => println("NPE " + e.getMessage)
case e => println("Other " + e.getMessage)
}
The type f: Throwable => Ucan also be Throwable => Unit, but I imitate the type of the return value of the function parameter on foreach. I can’t understand why it has a common return type instead of Unit.
source
share