What is a correct way to pass an array as a repeated parameter?
Explanation
Get an explanation when it's available:
Theory
  • The type of the repeated parameter inside the function is an Array of the declared type of the parameter. Nevertheless, if you have an array of the appropriate type, and attempt to pass it as a repeated parameter, you'll get a compiler error:
    
      scala> val arr = Array("What's", "up", "doc?")
      arr: Array[java.lang.String] = Array(What's, up, doc?)
      
      scala> echo(arr)
      :7: error: type mismatch;
       found   : Array[java.lang.String]
       required: String
             echo(arr)
                  ^
    
    To accomplish this, you'll need to append the array argument with a colon and an _* symbol, like this:
    
      scala> echo(arr: _*)
      What's
      up
      doc?
    
    This notation tells the compiler to pass each element of arr as its own argument to echo, rather than all of it as a single argument.
    Read more: Repeated parameters

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback