What does `:_*` (colon underscore star) do in Scala?

前端 未结 4 1791
悲&欢浪女
悲&欢浪女 2020-11-22 06:24

I have the following piece of code from this question:

def addChild(n: Node, newChild: Node) = n match {
  case Elem(prefix, label, attribs, scope, child @ _         


        
4条回答
  •  难免孤独
    2020-11-22 06:52

    All the above answer looks great, but just need a sample to explain this . Here it is :

    val x : Seq[Seq[Int]] = Seq(Seq(1),Seq(2))
    
    def f(arg: Seq[Any]*) : Int = {
     arg.length
    }
    f(x) //1 as x is taken as single arg
    f(x:_*)  // 2 as x is "unpacked" as a Seq[Any]*
    

    So now we know what :_* do is to tell compiler : please unpack this argument and bind those elements to the vararg parameter in function call rather than take the x as a single argument .

    So in a nutshell, the :_* is to remove ambiguity when pass argument to vararg parameter.

提交回复
热议问题