Scala - 可以取消应用返回可变参数吗?
下面的对象L1
可以工作。我可以通过传入 varargs 来“创建”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
是否可以以这种方式使用可变参数?
Object L1
below works. I can "create" an L1
by passing in varargs, which is nice, but I would like to be able to assign to an L1
using the same syntax. Unfortunately, the way I've done it here requires the uglier syntax of nesting an Array
inside the 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))
I attempted accomplish this in what seems like an obvious way, as in L2
below:
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))
But this give the error:
error: no `: _*' annotation allowed here
(such annotations are only allowed in arguments to *-parameters)`.
Is it possible for unapply
to use varargs in this way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你想要的是 unapplySeq。 Jesse Eichar 在 unapplySeq 上写了一篇很好的文章
I think what you want is unapplySeq. Jesse Eichar has a nice write up on unapplySeq