gpt4 book ai didi

scala - 在 case 语句中间使用 unapply 的对象

转载 作者:行者123 更新时间:2023-12-02 07:46:55 24 4
gpt4 key购买 nike

scala> object Test {
def unapply[L,R](v: (L, R)) = Some(v)
}
defined object Test

scala> (1, 2) match {
case 1 Test 2 => println("First")
case Test((1, 2)) => println("Second")
case _ => println("Third")
}
First

有人可以解释为什么第一个案例使用元组的两个值之间的对象吗?

最佳答案

来自Scala Specifications 8.1.10 :

Infix Operation Patterns
An infix operation pattern p;op;q is a shorthand for the constructor or extractor pattern op(p,q).

所以

case 1 Test 2 => println("First")

被重写为

case Test(1, 2) => println("First")
<小时/>

实际上,您可以通过添加 //print 在 REPL 中看到这一点在行尾并按 <tab>两次:

scala> (1, 2) match { case 1 Test 2 => println("First") } //print
scala.Tuple2.apply[Int, Int](1, 2) match {
case $line10.$read.$iw.$iw.Test(1, 2) => scala.Predef.println("First")
} // : Unit

关于scala - 在 case 语句中间使用 unapply 的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41684754/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com