目前我的代码需要类转换

val dataWriter: BytesDataWriter = createDataWriter

 def createDataWriter(p: SomeClass) =
    p.create_datawriter().asInstanceOf[BytesDataWriter]


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

08-18 10:35