5

I have an Option:

val myOption: Option[Int] = fooBar()

And a method that takes a varargs param:

def myMethod(a: String, b: Int*) = {...}

Is there any way to pass the option to the method as a varargs param? i.e. if the option is Some(3) then pass 3, and if it is None then pass nothing.

Experimenting with the answer to scala: How to pass an expanded list as varargs into a method? I tried explicitly typing the argument:

myMethod("xyz", myOption: _*)

but the compiler complains that it requires a Seq[Int]. It seems that Option does not implement Seq and there is no predef implicit conversion.

Given that the compiler wants a Seq, I can of course pass myOption.toList: _*, but is there a nicer way?

dbc
  • 104,963
  • 20
  • 228
  • 340
Chris B
  • 9,149
  • 4
  • 32
  • 38
  • What does your method require of a `Seq`? It's possible you can write it with more general collection operations (i.e. foreach, map, filter, etc.) – schmmd Nov 30 '11 at 18:26
  • @schmmd In this particular case, `myMethod` is part of a third-party library, so I have no choice but to use varargs. It it were my own code, I would probably just rewrite the method to take `Iterable[Int]` instead of `Int*`, and save myself all this trouble! – Chris B Dec 01 '11 at 00:44

1 Answers1

5
myMethod("xyz", myOption.toSeq: _*)
Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681