Having,
def test(args: Any*) = args.size
I'd like to call it with empty argument list depending on condition, but avoid if/else.
I've come out with this solution:
test(List("one").filter( _ => condition) : _*)
Is there better way than this?
For more context, I'm playing with Play 2.0 scala, and have this:
user => Redirect(routes.Application.index).withSession("username" -> user._1).withCookies(
List(Cookie("rememberme", Crypto.sign(user._1) + "-" + user._1)).filter(_ => user._3) : _*)
where user._3
is rembemberme boolean.
I'd like not to call withSession or call it with empty argument list (not to instantiate Cookie) if rememberme is false, in scala manner.
Thank you.
I think in this case embedding an if
/else
is the cleanest solution:
test((if (condition) Seq("one") else Seq.empty) : _*)
While Using list filter certainly works, it seems inappropriate here since you want either the entire list or an empty list and shouldn't need to iterate over the list members.
If you really want to avoid if/else, you could wrap the list in an Option[List[Any]]
and use the Option's filter
and getOrElse
methods
test(Some(List("one")).filter{_ => condition}.getOrElse(Nil): _*)
You could also use match
, which in this case is equivalent to if/else
test((condition match {case true => List("one"); case _ => Nil}) : _*)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With