Is there a difference between a method parameter String* and Array[String]?
Console:
scala> def main(args: Array[String]): Unit = {}
main: (args: Array[String])Unit
scala> def main(args: String*): Unit = {}
main: (args: String*)Unit
Code 1:
object Example {
def main(args: Array[String]): Unit = {
println("Hello")
}
}
>> Hello
Code 2:
object Example {
def main(args: String*): Unit = {
println("Hello")
}
}
>> Exception in thread "main" java.lang.NoSuchMethodException: Example.main([Ljava.lang.String;)
at java.lang.Class.getMethod(Class.java:1786)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:126)
Yes,
String* is a varargs, it takes in any number of Strings, which will be passed to the method as a Seq[String].
Array[String] take in a single Array of Strings.
If you have a sequence of String that you want to pass as a String*, you cannot do so directly, but you can "splat" out the sequence to pass it in using the :_* type ascription.
def varArg(input: String*){}
val strings = Seq("hello", "world")
varArg(strings:_*)
I went and asked on the forum.
The annotation you want is annotation.varargs.
I had some inkling that they had that glue, but I never had a reason to use it.
Personally, I'd rather it were automatic for a main method, b/c obvious.
$ scala
Welcome to Scala 2.12.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_131).
Type in expressions for evaluation. Or try :help.
scala> object Main { @annotation.varargs def main(args: String*) =
| println(args.size)
| }
defined object Main
scala> Main.main(Array("hello","world"): _*)
2
OK, cool.
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