Scala - 可以取消应用返回可变参数吗?

发布于 2024-11-17 08:25:37 字数 880 浏览 4 评论 0原文

下面的对象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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

青瓷清茶倾城歌 2024-11-24 08:25:37

我认为你想要的是 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

I think what you want is unapplySeq. Jesse Eichar has a nice write up on 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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文