Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass one or none variable arg in scala?

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.

like image 200
avalez Avatar asked Dec 17 '11 16:12

avalez


2 Answers

I think in this case embedding an if/else is the cleanest solution:

test((if (condition) Seq("one") else Seq.empty) : _*)
like image 59
kassens Avatar answered Oct 04 '22 11:10

kassens


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}) : _*)
like image 33
Dan Simon Avatar answered Oct 02 '22 11:10

Dan Simon