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
)
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.
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.
def foo(msf: String, o: AnyRef, os: AnyRef*) = println( String.format(msf, (o :: os.toList).toArray : _* ))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With