Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using varargs from Scala

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)

like image 231
oxbow_lakes Avatar asked Jun 17 '09 18:06

oxbow_lakes


People also ask

How do you pass variables in Scala?

The variable is declared with the following syntax in Scala as follows: val or val variable_name: variable_datatype = value; In the above syntax, the variable can be defined in one of two ways by using either the 'var' or 'val' keyword. It consists of 'variable_name' as your new variable, followed by a colon.

Is it good to use varargs in Java?

Varargs are useful for any method that needs to deal with an indeterminate number of objects. One good example is String. format . The format string can accept any number of parameters, so you need a mechanism to pass in any number of objects.


1 Answers

def foo(msf: String, o: AnyRef, os: AnyRef*) =    println( String.format(msf, (o :: os.toList).toArray : _* )) 
like image 107
James Iry Avatar answered Nov 09 '22 05:11

James Iry