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)?
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
}):_*)
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.
上一篇: Java可变参数传递lambda和值
下一篇: 默认情况下为可变参数空白的情况