简体   繁体   中英

scala syntax understanding _* and type*

I am having some difficulty in understanding this syntax:

(as: List[A]) =>    val h = insert(e, as: _*)}

and

def insert(h: H, as: A*): H = as.foldLeft(h)((hh, a) => insert(a, hh))

What do _* and A* mean?

Thanks.

A* is an argument define as a vararg, it's equivalent to A... in Java.

Exemple :

scala> def f(i: Int*) = i.length
f: (i: Int*)Int

scala> f(1,2,3)
res50: Int = 3

:_* is a transformer that allow to transform a param of type List into a vararg.

Exemple :

scala> f(List(1,2,3):_*)
res51: Int = 3
def insert(h: H, as: A*): H = as.foldLeft(h)((hh, a) => insert(a, hh))

A* represents a vararg : you can supply as many As as you wish to the method

(as: List[A]) =>    val h = insert(e, as: _*)}

in this case a Sequences is converted to a vararg parameter ( a single list is converted into n single arguments having the type of A).

sometimes this is necessary, imho it doesnt change too much on the conceptual level (as you still can invoke fold , map etc on both)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM