13
对象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
到以这种方式使用可变参数?
完美!谢谢! – dhg