我想从Scala中的文件中读取一个序列化对象,恢复类似于Python的pickle的功能。我破碎的物体阅读代码如下所示:
def ReadObjectFromFile[A](filename: String): A = {
val input = new ObjectInputStream(new FileInputStream(filename))
val obj = input.readObject()
obj match {
case a: A => a
case _ => sys.error("Type not what was expected when reading from file")
}
}
但是,此代码会导致警告“类型模式A中的抽象类型A未被选中,因为它已被擦除”。这样做的正确方法是什么?
答案 0 :(得分:1)
您可以使用implicits绕过类型擦除,如this blog post:
中所述def ReadObjectFromFile[A](filename: String)(implicit m:scala.reflect.Manifest[A]): A = {
val input = new ObjectInputStream(new FileInputStream(filename))
val obj = input.readObject()
obj match {
case x if m.erasure.isInstance(x) => x.asInstanceOf[A]
case _ => sys.error("Type not what was expected when reading from file")
}
}