修复序列化下的案例对象标识/模式匹配

时间:2012-03-27 16:16:06

标签: scala serialization equals case-class

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

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的树内调用并检索Tree$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

2 个答案:

答案 0 :(得分: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
...

答案 1 :(得分:1)

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

class Tree( val id: Int ) { /******/ }
object Tree {
  case object EmptyValue
}