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

后端 未结 4 1276
感动是毒
感动是毒 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:31

    You can get some way towards the Python using shapeless,

    Welcome to Scala version 2.11.0-20130208-073607-ce32c1af46 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_05).
    Type in expressions to have them evaluated.
    Type :help for more information.
    
    scala> import shapeless._
    import shapeless._
    
    scala> import Traversables._
    import Traversables._
    
    scala> case class ThreeValues(one: String, two: String, three: String)
    defined class ThreeValues
    
    scala> val argList = List("one","two","three")
    argList: List[String] = List(one, two, three)
    
    scala> argList.toHList[String :: String :: String :: HNil].map(_.tupled).map(ThreeValues.tupled)
    res0: Option[ThreeValues] = Some(ThreeValues(one,two,three))
    

    As you can see, a little more ceremony is required in Scala with shapeless. This is because shapeless imposes compile time constraints which are guaranteed to be satisfied at runtime (unlike the python, which will fail at runtime if args is the wrong size or contains elements of the wrong type) ... instead you're forced to specify the type you expect the List to have (in this case exactly three Strings) and be prepared to handle the case where that expectation isn't satisfied (because the result is explicitly an Option of ThreeValues).

提交回复
热议问题