Reputation: 31226
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.
Upvotes: 0
Views: 1034
Reputation: 2492
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.
Upvotes: 2