如何避免在Scala中使用asInstanceOf

Han*_*xue 2 factory casting scala classcastexception

目前我的代码需要类转换

val dataWriter: BytesDataWriter = createDataWriter

 def createDataWriter(p: SomeClass) =
    p.create_datawriter().asInstanceOf[BytesDataWriter]
Run Code Online (Sandbox Code Playgroud)

create_datawriter方法将返回超类DataWriter.asInstanceOf我尝试了这种方法,而不是使用它

val dataWriter: BytesDataWriter = createDataWriter(p)  match {
      case writer: BytesDataWriter => writer
      case _ => throw new ClassCastException
    }
Run Code Online (Sandbox Code Playgroud)

这太冗长了,如果情况不起作用.是否有更好的替代类铸造?

Ale*_*nov 8

如果您可以使用非结果执行某些操作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!")
}
Run Code Online (Sandbox Code Playgroud)

否则,请使用asInstanceOf.