1

我有一个在会话中被序列化和反序列化的类,我需要对内部类执行模式匹配。我在内部类的身份方面遇到问题:

class Tree(val id: Int) {
  override def hashCode = id
  override def equals(that: Any) = that.isInstanceOf[Tree] &&
    that.asInstanceOf[Tree].id == id

  case object EmptyValue
}

val t1 = new Tree(33)
val t2 = new Tree(33)

t1 == t2 // ok 
t1.EmptyValue == t2.EmptyValue // wrong -- reports 'false'

可以说,什么是一种优雅的方式来修复身份EmptyValue而不是“逃避路径依赖”。我有如下代码,当序列化发生时会中断:

def insert(point: Point, leaf: Leaf): Unit = {
  val qidx = hyperCube.indexOf(point)
  child(qidx) match {
    case EmptyValue => ...
    ...
  }
}

也就是说,尽管编译器说我的匹配是详尽的,但在使用序列化时我得到了一个运行MatchError时(我有自定义代码可以写入/读取字节数组)。例如,我从树中调用Tree$EmptyValue$@4636并检索 aTree$EmptyValue$@3601并且它们不匹配。

编辑

我进行了进一步的测试,因为我真的很想避免将内部类型移出,因为它们需要具有类型参数,从而破坏所有模式匹配代码。看起来好像问题只发生在那个特定的case object

class Tree {
  sealed trait LeftChild
  case object  EmptyValue   extends LeftChild
  sealed trait LeftNonEmpty extends LeftChild
  final case class LeftChildBranch() extends LeftNonEmpty

  def testMatch1(l: LeftChild) = l match {
    case EmptyValue        => "empty"
    case LeftChildBranch() => "non-empty"
  }

  def testMatch2(l: LeftChild) = l match {
    case EmptyValue      => "empty"
    case n: LeftNonEmpty => "non-empty"
  }
}

val t1 = new Tree
val t2 = new Tree

t1.testMatch1(t2.LeftChildBranch().asInstanceOf[t1.LeftChild])       // works!!!
t1.testMatch2(t2.LeftChildBranch().asInstanceOf[t1.LeftChild])       // works!!!
t1.testMatch1(t2.EmptyValue.asInstanceOf       [t1.EmptyValue.type]) // fails
4

2 回答 2

2

存在类型可以表达这一点。

scala> case class Tree(id: Int) {
     |    case object EmptyValue {
     |       override def hashCode = 0
     |       override def equals(that: Any) = that.isInstanceOf[x.EmptyValue.type forSome { val x: Tree }]
     |    }
     | }
defined class Tree

scala> val t1 = Tree(33)
t1: Tree = Tree(33)

scala> val t2 = Tree(33)
t2: Tree = Tree(33)

scala> t1.EmptyValue == t2.EmptyValue
res0: Boolean = true

字节码equals

scala> :javap -v Tree.EmptyValue

...
public boolean equals(java.lang.Object);
  Code:
   Stack=1, Locals=2, Args_size=2
   0:   aload_1
   1:   instanceof  #23; //class Tree$EmptyValue$
   4:   ireturn
...
于 2012-03-27T16:49:30.767 回答
1

如果我理解您要正确执行的操作,您可以尝试为 Tree 添加一个伴随对象并在其中定义 EmptyValue:

class Tree( val id: Int ) { /******/ }
object Tree {
  case object EmptyValue
}
于 2012-03-27T16:23:47.847 回答