Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Is there a difference between method parameter String* and Array[String]

Tags:

scala

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)
like image 845
rapt Avatar asked Apr 20 '26 19:04

rapt


2 Answers

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:_*)
like image 141
puhlen Avatar answered Apr 24 '26 00:04

puhlen


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.

like image 42
som-snytt Avatar answered Apr 24 '26 01:04

som-snytt