Syntax sugar: _* for treating Seq as method parameters
Asked Answered
P

3

50

I just noticed this construct somewhere on web:

val list = List(someCollection: _*)

What does _* mean? Is this a syntax sugar for some method call? What constraints should my custom class satisfy so that it can take advantage of this syntax sugar?

Palila answered 14/11, 2010 at 6:22 Comment(0)
F
74

Generally, the : notation is used for type ascription, forcing the compiler to see a value as some particular type. This is not quite the same as casting.

val b = 1 : Byte
val f = 1 : Float
val d = 1 : Double

In this case, you're ascribing the special varargs type. This mirrors the asterisk notation used for declaring a varargs parameter and can be used on a variable of any type that subclasses Seq[T]:

def f(args: String*) = ... //varargs parameter, use as an Array[String]
val list = List("a", "b", "c")
f(list : _*)
Forestforestage answered 14/11, 2010 at 10:23 Comment(1)
i tried returning an array of String like String* , i get an error that cannot resolve * . If i return Array[String] and pass it to a method with args (args: String*) it says expecting String and not Array[String]Joubert
D
18

That's scala syntax for exploding an array. Some functions take a variable number of arguments and to pass in an array you need to append : _* to the array argument.

Dracula answered 14/11, 2010 at 6:57 Comment(1)
Nitpick: the argument need only be a Seq, or implicitly convertible to a Seq.Padnag
L
1

Variable (number of) Arguments are defined using *. For example,

def wordcount(words: String*) = println(words.size)

wordcount expects a string as parameter,

scala> wordcount("I")
1

but accepts more Strings as its input parameter (_* is needed for Type Ascription)

scala> val wordList = List("I", "love", "Scala")
scala> wordcount(wordList: _*)
3
Longitude answered 7/1, 2019 at 0:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.