首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >unapply和unapplySeq有什么区别?

unapply和unapplySeq有什么区别?
EN

Stack Overflow用户
提问于 2011-11-27 06:59:19
回答 3查看 9K关注 0票数 41

为什么Scala同时有unapplyunapplySeq?两者之间的区别是什么?什么时候我应该更喜欢其中的一个呢?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-11-27 09:09:59

不深入细节并稍微简化一下:

对于常规参数apply构造和unapply解构:

代码语言:javascript
复制
object S {
  def apply(a: A):S = ... // makes a S from an A
  def unapply(s: S): Option[A] = ... // retrieve the A from the S
}
val s = S(a)
s match { case S(a) => a } 

对于重复的参数、apply构造和unapplySeq解构:

代码语言:javascript
复制
object M {
  def apply(a: A*): M = ......... // makes a M from an As.
  def unapplySeq(m: M): Option[Seq[A]] = ... // retrieve the As from the M
}
val m = M(a1, a2, a3)
m match { case M(a1, a2, a3) => ... } 
m match { case M(a, as @ _*) => ... } 

请注意,在第二种情况下,重复的参数被视为Seq以及A*_*之间的相似性。

因此,如果您想要对自然包含各种单一值的内容进行解构,请使用unapply。如果想要解构包含Seq的内容,请使用unapplySeq

票数 39
EN

Stack Overflow用户

发布于 2011-11-27 07:43:31

固定性与可变性。Pattern Matching in Scala (pdf)通过镜像示例很好地解释了这一点。我在this answer中也有镜像的例子。

简要地说:

代码语言:javascript
复制
object Sorted {
  def unapply(xs: Seq[Int]) =
    if (xs == xs.sortWith(_ < _)) Some(xs) else None
}

object SortedSeq {
  def unapplySeq(xs: Seq[Int]) =
    if (xs == xs.sortWith(_ < _)) Some(xs) else None
}

scala> List(1,2,3,4) match { case Sorted(xs) => xs }
res0: Seq[Int] = List(1, 2, 3, 4)
scala> List(1,2,3,4) match { case SortedSeq(a, b, c, d) => List(a, b, c, d) }
res1: List[Int] = List(1, 2, 3, 4)
scala> List(1) match { case SortedSeq(a) => a }
res2: Int = 1

那么,您认为下面的示例中展示了哪一个?

代码语言:javascript
复制
scala> List(1) match { case List(x) => x }
res3: Int = 1
票数 18
EN

Stack Overflow用户

发布于 2019-04-27 11:01:20

下面是一些例子:

代码语言:javascript
复制
scala> val fruit = List("apples", "oranges", "pears")
fruit: List[String] = List(apples, oranges, pears)

scala> val List(a, b, c) = fruit
a: String = apples
b: String = oranges
c: String = pears

scala> val List(a, b, _*) = fruit
a: String = apples
b: String = oranges

scala> val List(a, _*) = fruit
a: String = apples

scala> val List(a,rest @ _*) = fruit
a: String = apples
rest: Seq[String] = List(oranges, pears)

scala> val a::b::c::Nil = fruit
a: String = apples
b: String = oranges
c: String = pears

scala> val a::b::rest = fruit
a: String = apples
b: String = oranges
rest: List[String] = List(pears)

scala> val a::rest = fruit
a: String = apples
rest: List[String] = List(oranges, pears)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8282277

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档