Using varargs from Scala

ScalaVariadic Functions

Scala Problem Overview


I'm tearing my hair out trying to figure out how to do the following:

def foo(msf: String, o: Any, os: Any*) = {
    println( String.format(msf, o :: List(os:_*)) )
}

There's a reason why I have to declare the method with an o and an os Seq separately. Basically, I end up with the format method called with a single object parameter (of type List ). Attempting:

def foo(msf: String, o: Any, os: Any*) = {
    println( String.format(msf, (o :: List(os:_*))).toArray )
}

Gives me the type error: > found: Array[Any] > > required Seq[java.lang.Object]

I've tried casting, which compiles but fails for pretty much the same reason as the first example. When I try

println(String.format(msg, (o :: List(os:_*)) :_* ))

this fails to compile with implicit conversion ambiguity (any2ArrowAssoc and any2stringadd)

Scala Solutions


Solution 1 - Scala

def foo(msf: String, o: AnyRef, os: AnyRef*) = 
  println( String.format(msf, (o :: os.toList).toArray : _* ))

Solution 2 - Scala

def foo(msf: String, o: AnyRef, os: AnyRef*) =
  println( String.format(msf, o :: os.toList : _* ) )

or

def foo(msf: String, o: AnyRef, os: AnyRef*) =
      println( msf format (o :: os.toList : _* ) )

I much prefer the latter, though it has no locale* support.

  • Scala 2.8 does have locale support with RichString's format.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionoxbow_lakesView Question on Stackoverflow
Solution 1 - ScalaJames IryView Answer on Stackoverflow
Solution 2 - ScalaDaniel C. SobralView Answer on Stackoverflow