目前我的代码需要类转换
val dataWriter: BytesDataWriter = createDataWriter
def createDataWriter(p: SomeClass) =
p.create_datawriter().asInstanceOf[BytesDataWriter]
The create_datawriter
方法将返回超类DataWriter。而不是使用它来投射它asInstanceOf
,我尝试过这种方法
val dataWriter: BytesDataWriter = createDataWriter(p) match {
case writer: BytesDataWriter => writer
case _ => throw new ClassCastException
}
这太冗长了,万一情况不起作用。除了班级选角之外,还有更好的选择吗?
如果可以的话,您可以使用第二种方法某物与非BytesDataWriter
结果,或者获得更好的错误消息:
val dataWriter: BytesDataWriter = p.create_datawriter() match {
case writer: BytesDataWriter => writer
case other => throw new Exception(s"Expected p to create a BytesDataWriter, but got a ${other.getClass.getSimpleName} instead!")
}
否则,使用asInstanceOf
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)