问题描述
为什么 Scala 有 unapply
和 unapplySeq
?两者有什么区别?我什么时候应该更喜欢一个?
Why does Scala have both unapply
and unapplySeq
? What is the difference between the two? When should I prefer one over the other?
推荐答案
不深入细节和简化一点:
Without going into details and simplifying a bit:
对于常规参数 apply
构造和 unapply
解构:
For regular parameters apply
constructs and unapply
de-structures:
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
解构:
For repeated parameters, apply
constructs and unapplySeq
de-structures:
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*
和 _*
之间的相似性.
Note that in that second case, repeated parameters are treated like a Seq
and the similarity between A*
and _*
.
因此,如果您想解构自然包含各种单个值的内容,请使用 unapply
.如果您想解构包含 Seq
的内容,请使用 unapplySeq
.
So if you want to de-structure something that naturally contains various single values, use unapply
. If you want to de-structure something that contains a Seq
, use unapplySeq
.
这篇关于unapply 和 unapplySeq 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!