pml*_*mlt 3 scala pattern-matching
我注意到关于没有任何参数列表的案例类(不是案例对象)的非常奇怪的行为.在尝试对它们进行模式匹配时,似乎完全忽略了超类型.我写了一个小例子来展示行为:
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)
}
}
Run Code Online (Sandbox Code Playgroud)
该程序的输出如下:
(This is a common type,A(1))
(This is not a common type,B)
(This is a common type,C)
Run Code Online (Sandbox Code Playgroud)
这是一个错误吗?任何人都可以解释为什么Scala会这样做吗?
这是因为B没有实例化B; 它只是一个表示类型的对象:
scala> B
res0: B.type = B
Run Code Online (Sandbox Code Playgroud)
类B的对象也是特征的对象CommonType,但类型对象B既不是.
添加括号实际上会实例化对象,因此它可以工作:
scala> B()
res1: B = B()
scala> printifmatched(B())
(This is a common type, B())
Run Code Online (Sandbox Code Playgroud)
顺便说一下,不推荐使用不带括号的case类定义:
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
^
Run Code Online (Sandbox Code Playgroud)
它适用于case对象,因为对象不需要参数,因为它们不需要实例化.C是对C类型(单例)实例的引用.
| 归档时间: |
|
| 查看次数: |
1031 次 |
| 最近记录: |