任何人都可以解释对象行为的模式匹配。 同一类的两个对象是否相同?
object Solution extends App {
case class EE() { }
object EE1 extends EE
object EE2 extends EE
val k: EE = EE1
println(k.getClass) // class Solution$EE1$
println(k.isInstanceOf[EE2.type]) // returns FALSE
println(k.getClass.isInstanceOf[EE2.type.getClass]) // returns FALSE
k match {
case EE2 => println("EE1 match EE2!!!") // MATCH THIS LINE/// WHY???
case EE1 => println("EE1 match EE1. OK!")
}
}
答案 0 :(得分:6)
当你在匹配中写case EE2
时,它会检查匹配的对象是否与EE2
相等(请注意,如果标识符以小写字母开头,那么Lee的回答是正确的;此规则专门用于匹配object
和常量,其名称通常以大写字母开头,有意义)。但由于EE1
和EE2
都延伸case class EE()
,因此它们相等(您可以直接使用EE1 == EE2
或k == EE2
进行检查)。如果你使它们不等by removing case
:
object Solution extends App {
class EE() { }
object EE1 extends EE
object EE2 extends EE
val k: EE = EE1
println(k.getClass) // class Solution$EE1$
println(k.isInstanceOf[EE2.type]) // returns FALSE
k match {
case EE2 => println("EE1 match EE2!!!") // MATCH THIS LINE/// WHY???
case EE1 => println("EE1 match EE1. OK!")
}
}
Processing...
Reused last reload result
[info] Loading project definition from /tmp/renderer9oHZD8Bvx9/project/project
[info] Loading project definition from /tmp/renderer9oHZD8Bvx9/project
[info] Set current project to rendererWorker (in build file:/tmp/renderer9oHZD8Bvx9/)
[info] Reapplying settings...
[info] Set current project to rendererWorker (in build file:/tmp/renderer9oHZD8Bvx9/)
[info] Formatting 1 Scala source {file:/tmp/renderer9oHZD8Bvx9/}rendererWorker(compile) ...
[info] Reformatted 1 Scala source {file:/tmp/renderer9oHZD8Bvx9/}rendererWorker(compile).
[info] Compiling 1 Scala source to /tmp/renderer9oHZD8Bvx9/target/classes...
[success] Total time: 4 s, completed Aug 19, 2015 1:13:04 PM
Now running...
[info] Running Solution
class Solution$EE1$
false
EE1 match EE1. OK!
[success] Total time: 0 s, completed Aug 19, 2015 1:13:04 PM