I have a case class like this:
case class AEMError(
authError: Option[AEMAuthError] = None,
unexpectedError: Option[AEMUnexpectedError] = None,
)
I want to do a pattern matching like this:
def throwErrorAndLogMessage(error:AEMError,message:String):Unit={
error match {
case authError: Some[AEMAuthError] => {???}
case unexpectedError: Some[AEMUnexpectedError] => {???}
case _ => {???}
}
}
and add multiple case classes for different types of error but I am totally spinning on the syntax for case match can somebody help me here?
CodePudding user response:
With your definition of AEMError
you can't do reasonable pattern matching because it possible to have both error present.
You should change AEMError
to
sealed trait AEMError
case class AEMErrorAuth(authError: AEMAuthError) extends AEMError
case class AEMErrorUnexpected(authError: AEMUnexpectedError) extends AEMError
And use it like this:
err match {
case AEMErrorAuth(authError) => {
print(authError)
}
case AEMErrorUnexpected(unexpectedError) => {
print(unexpectedError)
}
}
CodePudding user response:
If you can't change the signature of AEMError
like @talex mentioned, you can try something like:
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 _ => ???
}
}