【发布时间】:2011-09-23 23:13:35
【问题描述】:
下面的对象L1 有效。我可以通过传入可变参数来“创建”L1,这很好,但我希望能够使用相同的语法分配给L1。不幸的是,我在这里的做法需要在L1 中嵌套Array 的更难看的语法。
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 可以这样使用可变参数吗?
【问题讨论】:
标签: scala variadic-functions unapply