gpt4 book ai didi

scala - 匹配没有参数列表的案例类

转载 作者:行者123 更新时间:2023-12-01 08:59:41 25 4
gpt4 key购买 nike

我注意到关于没有任何参数列表的案例类(不是案例对象)的非常奇怪的行为。在尝试对它们进行模式匹配时,似乎完全忽略了父类(super class)型。我写了一个小例子来展示这种行为:

object TestMatch {
trait CommonType
case class A(val x:Int) extends CommonType
case class B extends CommonType
case object C extends CommonType

def main(args: Array[String]): Unit = {
printifmatched(A(1))
printifmatched(B)
printifmatched(C)
}
def printifmatched: PartialFunction[Any,Unit] = {
case x: CommonType => println("This is a common type", x)
case x => println("This is not a common type", x)
}
}

这个程序的输出如下:

(This is a common type,A(1))
(This is not a common type,B)
(This is a common type,C)

这是一个错误吗?谁能解释一下为什么 Scala 会这样?

最佳答案

这是因为B没有实例化一个B;它只是一个表示类型的对象:

scala> B
res0: B.type = B

B 类的对象也是 trait CommonType 的对象,但 B 的类型对象都不是。

添加括号实际上是实例化对象,所以它可以工作:

scala> B()
res1: B = B()

scala> printifmatched(B())
(This is a common type, B())

顺便说一句,不推荐使用不带括号的案例类:

scala> case class B
<console>:1: warning: case classes without a parameter list have been deprecated;
use either case objects or case classes with `()' as parameter list.
case class B
^

它适用于 case 对象,因为对象不需要参数,因为它们不需要被实例化。 C 是对 C 类型(单例)实例的引用。

关于scala - 匹配没有参数列表的案例类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20083703/

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