Question

I'm using XStream in my Scala app with the following thin wrapper:

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)
  } 
}   

Is this the best I'm going to get, or is there a way around that asInstanceOf? It looks like casting is the recommended usage in Java; I'm wondering if Scala provides me some cleaner option.

Was it helpful?

Solution

You can avoid the asInstanceOf, but the advantages are limited -- the code becomes more idiomatic and you can make the ClassCastException more specific:

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)
}

On the other hand, this is more verbose and probably less efficient than the asInstanceOf call.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top