为什么Scala同时拥有unapply
和unapplySeq
?两者有什么区别?我什么时候应该更喜欢一个?
答案 0 :(得分:30)
没有详细说明和简化:
对于常规参数apply
构造和unapply
去构造:
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
去结构:
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
。
答案 1 :(得分:18)
固定arity与变量arity。 Pattern Matching in Scala (pdf)通过镜像示例解释得很清楚。我在this answer中也有镜像示例。
简言之:
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
那么,您认为哪个会在以下示例中展示?
scala> List(1) match { case List(x) => x }
res3: Int = 1
答案 2 :(得分:0)
一些例子:
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)