I'm rather new to Scala and stumbled upon a small little issue that keeps bothering me. Let's say there is some method with default parameter
def foo(v: Any = "default"): String = s"called with parameter '$v'"
and an Option val opt: Option[String]
.
How to call this method with either the option value (if defined) or the default parameter?
I mean despite the obvious solution
val result = if (opt.isDefined)
from.here.to.foo(opt.get)
else
from.here.to.foo()
and having to type the method with (possibly long) object chain twice? Not to mention having more than one optional/default parameter...
All I could come up with is the unhelpful helper
def definedOrDefault[A, B](opt: Option[A], f0: => B, f1: A => B): B =
if (opt.isDefined) f1(opt.get) else f0
but when not being able to mention default parameters in higher order functions... that's it. Reminds me of the bad old days with Java where method overloading creates the same problem.