Scala - 可以取消应用返回varargs?

dhg*_*dhg 13 scala variadic-functions unapply

L1下面的对象有效.我可以L1通过传入varargs 来"创建" ,这很好,但我希望能够L1使用相同的语法分配给一个.不幸的是,我在这里完成它的方式需要更粗略的嵌套Array内部语法L1.

object L1 {
    def apply(stuff: String*) = stuff.mkString(",")
    def unapply(s: String) = Some(s.split(","))
}
val x1 = L1("1", "2", "3")
val L1(Array(a, b, c)) = x1
println("a=%s, b=%s, c=%s".format(a,b,c))
Run Code Online (Sandbox Code Playgroud)

我尝试以一种显而易见的方式实现这一目标,L2如下所示:

object L2 {
    def apply(stuff: String*) = stuff.mkString(",")
    def unapply(s: String) = Some(s.split(","):_*)
}
val x2 = L2("4", "5", "6")
val L2(d,e,f) = x2
println("d=%s, e=%s, f=%s".format(d,e,f))
Run Code Online (Sandbox Code Playgroud)

但是这给出了错误:

error: no `: _*' annotation allowed here 
(such annotations are only allowed in arguments to *-parameters)`.
Run Code Online (Sandbox Code Playgroud)

是否有可能unapply以这种方式使用varargs?

jsu*_*eth 22

我想你想要的是unapplySeq.Jesse Eichar在unapplySeq写得很好

scala> object L2 {
     |     def unapplySeq(s: String) : Option[List[String]] = Some(s.split(",").toList)
     |     def apply(stuff: String*) = stuff.mkString(",")
     | }
defined module L2

scala> val x2 = L2("4", "5", "6")
x2: String = 4,5,6

scala> val L2(d,e,f) = x2
d: String = 4
e: String = 5
f: String = 6
Run Code Online (Sandbox Code Playgroud)