在不使用asInstanceOf的情况下在Scala中反序列化XStream中的XML?

时间:2013-12-20 17:52:46

标签: scala xstream

我在我的Scala应用程序中使用XStream,使用以下瘦包装器:

import com.thoughtworks.xstream._

object SXStream {
  private val xstream = new XStream

  def fromXML[T](xml: String): T = {
    xstream.fromXML(xml).asInstanceOf[T]
  } 

  def toXML[T](obj: T): String = {
    xstream.toXML(obj)
  } 
}   

这是我能得到的最好的,还是有办法解决asInstanceOf?看起来像是Java中的推荐用法;我想知道Scala是否为我提供了一些更清洁的选择。

1 个答案:

答案 0 :(得分:2)

您可以避开asInstanceOf,但优势有限 - 代码变得更加惯用,您可以使ClassCastException更具体:

def any(xml: String): Any = xml
def fromXML[T: ClassTag](xml: String): T = any(xml) match {
  case a: T => a
  case other => throw new RuntimeException("Invalid type " + other.getClass + " found during marshalling of xml " + xml)
}

另一方面,这比asInstanceOf电话更加冗长,效率可能更低。

相关问题