13

下面的对象L1有效。我可以通过传入可变参数来“创建”一个L1,这很好,但我希望能够L1使用相同的语法分配给一个。不幸的是,我在这里完成的方式需要ArrayL1.

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))

我试图以一种显而易见的方式完成此任务,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))

但这给出了错误:

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

是否可以unapply以这种方式使用可变参数?

4

1 回答 1

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
于 2011-06-28T03:10:30.223 回答