How to pass one or none arg variable in scala?

Having,

def test(args: Any*) = args.size

I would call it an empty argument list depending on the condition, but avoid if / else.

I came up with this solution:

test(List("one").filter( _ => condition) : _*)

Is there a better way than this?

For more context, I play with Play 2.0 scala and get the following:

  user => Redirect(routes.Application.index).withSession("username" -> user._1).withCookies(
    List(Cookie("rememberme", Crypto.sign(user._1) + "-" + user._1)).filter(_ => user._3) : _*)

where user._3is rembemberme boolean.

I would not call Session or call it with an empty argument list (not to create an instance of Cookie) if memme is false, in a scala way.

Thank.

+5
source share
2 answers

I think in this case, embedding if/ elseis the cleanest solution:

test((if (condition) Seq("one") else Seq.empty) : _*)
+7
source

, , , , , .

if/else, Option[List[Any]] filter getOrElse

test(Some(List("one")).filter{_ => condition}.getOrElse(Nil): _*)

match, if/else

test((condition match {case true => List("one"); case _ => Nil}) : _*)
+3

All Articles