Milo Wielondek
Milo Wielondek

Reputation: 4352

Default empty case for varargs

Say you wish to use pattern matching when calling a method with varargs like so:

def foo(bar: Int*) = ???

val x = false
foo(x match {
  case true => 1
  case _ =>
})

Running the above code results in type mismatch error, since foo requires an argument of type Int but found Unit instead in the default case. Removing the default case, on the other hand, results in a warning that the match may not be exhaustive, and rightfully so.

My question is, how do I supply an empty default case for the match (which would result in calling foo() without any arguments)?

Upvotes: 2

Views: 774

Answers (2)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

One option would be to use an Option[Int] instead of an Int:

def foo(bar: Option[Int]*) = ???

val x = false
foo(x match {
  case true => Some(1)
  case _ => None
})

I think an if-else expression would be less verbose here:

foo(if (x) Some(1) else None)

I'd argue though that if you're matching over a single Boolean there's no point in passing varargs at all.

Upvotes: 2

alextsc
alextsc

Reputation: 1368

You could capture the match result in a sequence and represent the lack of arguments as an empty one. Then just splat the result into the parameter:

val x = true
foo((x match {
  case true => Seq(1)
  case _ => Seq.empty
}):_*)

Upvotes: 3

Related Questions