Suppose I have a function f: Int => String which may throw exceptions. I would like to write a function tryF(f: Int => String, arg: Int, defaultOpt: Option[String]), which works as follows:
- Invoke
f(arg)and return the result if it has thrown no exception - if the invocation has failed with an exception and
defaultOpt.isDefinedthen returndefaultOpt.get - Otherwise throw the exception
I am writing it as follows:
def tryF(f: Int => String, arg: Int, defaultOpt: Option[String]) = {
val r = scala.util.Try(f(arg))
r.toOption orElse defaultOpt getOrElse r.get
}
Does it make sense ? Would you rewrite it ?