首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我可以使用抽象类型来匹配案例类吗?

我可以使用抽象类型来匹配案例类吗?
EN

Stack Overflow用户
提问于 2013-03-10 03:16:28
回答 2查看 107关注 0票数 1

或者,换句话说:尽管元组的字段(参数)有不同的值,但元组中的元素是否属于相同的case类,是否可以通过匹配进行验证?下面有类似于caseT的东西吗?

代码语言:javascript
复制
sealed abstract class RootClass
case class ChildClassX(valuex: Boolean) extends RootClass
case class ChildClassY(valuey: Boolean) extends RootClass
// and other case classes here...

object Foo {
def compare(a: RootClass, b: RootClass) = {
    (a, b) match {
       case[T] (T(a), T(b)) => a == b
       case _ => throw Exception("a and b should be of same child classes.")
    }
}

我希望我不必这样做:

代码语言:javascript
复制
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.")
    }
}

相关:matching

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-03-10 05:44:09

我能想到的最合理的解决方案是简单地比较这两个项的类。

代码语言:javascript
复制
(a, b) match {
  case (x,y) if x.getClass == y.getClass => "matching classes"
  case _ => "no match"
}

我不知道有任何像您描述的那样工作的构造,比如case[T]

票数 2
EN

Stack Overflow用户

发布于 2013-03-10 05:07:55

我想,这将是一个解决方案--如果它真的只涉及到类:

代码语言:javascript
复制
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)
}

没有匹配..。也许有人有更优雅的解决方案?但这可能是最短的..。

示例测试代码:

代码语言:javascript
复制
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))
}

指纹:

代码语言:javascript
复制
true
false
true
Exception in thread "main" scala.MatchError: a and b should be of same child classes. 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15318502

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档