Can I use abstract types in matching of case classes?
或者,换句话说:
我可以通过匹配验证元组中的元素是否具有相同的case类,尽管它们的字段(参数)中的值不同?
是否有与下面的case [T]等效的东西?
我希望我不必做:
1 2 3 4 5 6 7
| object Foo {
def compare (a : RootClass, b : RootClass ) = {
(a, b ) match {
case (ChildClassX (a ), ChildClassX (b )) | (ChildClassY (a ), ChildClassY (b )) | (ChildClassZ (a ), ChildClassZ (b )) | etc. => a == b
case _ => throw Exception ("a and b should be of same child classes.")
}
} |
相关:
匹配
- 为什么不将Foo中的compare定义为:def compare(a: RootClass, b: RootClass) = a == b?如果返回false,则让调用方处理类型检查。似乎更符合比较功能的期望?
-
很好,但是我在这里称它为"比较"会引起误解。实际上,这是一个"案例",降级到案例类的树上。
我能想到的最合理的解决方案是简单地比较两个项目的类。
1 2 3 4
| (a, b ) match {
case (x,y ) if x. getClass == y. getClass =>"matching classes"
case _ =>"no match"
} |
我不知道有什么结构可以像您描述的那样工作,例如case[T]。
- 比我目前使用isInstanceOfs或很多情况的代码要好:)
-
如果使用这种方法,您必须要注意的是子类:class A; class B extends A; val a1: A = new A; val a2: A = new B; a1.getClass != a2.getClass-尽管从技术上讲,它们都是A的实例,但getClass仍会返回该实例的类,这会使事情变得混乱方法。
-
没关系,这是我需要的行为。
我想这将是一个解决方案-如果它确实仅与类有关:
1 2 3 4 5 6
| object Foo {
def compare [A,B ](a : A, b : B ) =
if (a. getClass. getSuperclass != b. getClass. getSuperclass)
throw new MatchError ("a and b should be of same child classes.")
else (a. getClass == b. getClass)
} |
不涉及匹配...也许有人有一个更优雅的解决方案?但这可能是最短的...
测试代码示例:
1 2 3 4 5 6 7 8
| object ObjCmp extends App {
case object X
val p : Product = ChildClassX (true)
println (Foo. compare(ChildClassX (true), ChildClassX (false)))
println (Foo. compare(ChildClassX (true), ChildClassY (false)))
println (Foo. compare(ChildClassX (true), p ))
println (Foo. compare(ChildClassX (true), X ))
} |
打印:
1 2 3 4
| true
false
true
Exception in thread "main" scala. MatchError: a and b should be of same child classes. |