Scala's allowed duplicate parameters

Source: Internet
Author: User

Scala allows you to indicate that the last parameter of a function can be duplicated. This allows the customer to pass the variable-length argument list to the function. To mark a repeating parameter, place an asterisk after the type of the argument. For example:

Scala> def Echo

(args:string*) = for
(Arg <-args) println (ARG)
Echo: (string*) unit

This defines that echo can be invoked by 0 to multiple string arguments:

Scala> Echo ()
scala> Echo ("one")
one
scala> echo ("Hello", "world!")
Hello
world!

Inside a function, the type of the repeating parameter is an array that declares the parameter type. Thus, the type of args declared as type "string*" in the Echo function is actually array[string]. However, if you have an array of the appropriate type and try to pass it as a repeating parameter, you get a compiler error:

scala> val arr = Array

("What", "Up", "Doc?")
Arr:array[java.lang.string] = Array (What ' s, up, Doc?)
Scala> Echo (arr)
< console>:7:error:type mismatch;
found:array[java.lang.string]
required : String
Echo (arr)
ˆ

To implement this, you need to add a colon and a _* symbol after the array argument, like this:

Scala> Echo (arr: _*)
What ' s
up
Doc?

This annotation tells the compiler to take each element of arr as a parameter instead of passing it as a single argument to echo.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.