Is there a Scala equivalent of the Python list unpack (a.k.a. “*”) operator?

后端 未结 4 1270
感动是毒
感动是毒 2021-02-07 01:16

In Python, we have the star (or \"*\" or \"unpack\") operator, that allows us to unpack a list for convenient use in passing positional arguments. For example:

         


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-07 01:50

    There is no direct equivalent in scala. The closest thing you will find is the usage of _*, which works on vararg methods only. By example, here is an example of a vararg method:

    def hello( names: String*) {
      println( "Hello " + names.mkString(" and " ) )
    }
    

    which can be used with any number of arguments:

    scala> hello()
    Hello
    scala> hello("elwood")
    Hello elwood
    scala> hello("elwood", "jake")
    Hello elwood and jake
    

    Now, if you have a list of strings and want to pass them to this method, the way to unpack it is through _*:

    scala> val names = List("john", "paul", "george", "ringo")
    names: List[String] = List(john, paul, george, ringo)
    scala> hello( names: _* )
    Hello john and paul and george and ringo    
    

提交回复
热议问题