我有一個這樣的案例類:
case class AEMError(
authError: Option[AEMAuthError] = None,
unexpectedError: Option[AEMUnexpectedError] = None,
)
我想做這樣的模式匹配:
def throwErrorAndLogMessage(error:AEMError,message:String):Unit={
error match {
case authError: Some[AEMAuthError] => {???}
case unexpectedError: Some[AEMUnexpectedError] => {???}
case _ => {???}
}
}
并為不同型別的錯誤添加多個案例類,但我完全在使用案例匹配的語法,有人可以幫我嗎?
uj5u.com熱心網友回復:
根據您的定義,AEMError您無法進行合理的模式匹配,因為可能同時存在兩個錯誤。
你應該AEMError改為
sealed trait AEMError
case class AEMErrorAuth(authError: AEMAuthError) extends AEMError
case class AEMErrorUnexpected(authError: AEMUnexpectedError) extends AEMError
并像這樣使用它:
err match {
case AEMErrorAuth(authError) => {
print(authError)
}
case AEMErrorUnexpected(unexpectedError) => {
print(unexpectedError)
}
}
uj5u.com熱心網友回復:
如果您無法更改AEMError提到的 @talex 的簽名,您可以嘗試以下操作:
def throwErrorAndLogMessage(error: AEMError, message: String): Unit = {
error match {
case AEMError(Some(authError), Some(unexpectedError)) => ???
case AEMError(Some(authError), None) => ???
case AEMError(None, Some(unexpectedError)) => ???
case _ => ???
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/512171.html
標籤:斯卡拉模式匹配
上一篇:如何在腳本運行時運行生成的代碼?
