Michal Klimczak
08/04/2023, 2:32 PMsealed interface GeneralFormError {
object FieldRequired : GeneralFormError
}
sealed interface SpecificFormError : GeneralFormError {
object PostCodeInvalid : SpecificFormError
}
fun GeneralFormError.message() : String = when(this) {
GeneralFormError.FieldRequired -> "Field is required"
else -> throw IllegalStateException("Subtype of GeneralFormError not handled")
}
fun SpecificFormError.message() : String = when(this) {
SpecificFormError.PostCodeInvalid -> "Post code is invalid"
is GeneralFormError -> (this as GeneralFormError).message()
}
Then I have a variable val postCodeError : GeneralFormError
which can be both FieldRequired
or PostCodeInvalid
. If I call postCodeError.message()
it will throw the ISE. Is there an elegant way of doing this properly (without checking the type in use site).ephemient
08/05/2023, 12:18 AMis SpecificFormError -> message() // this calls the SpecificFormError overload since it has been smart casted
to GeneralFormError.message()
Michal Klimczak
08/05/2023, 4:42 AMephemient
08/05/2023, 4:59 AMephemient
08/05/2023, 5:01 AM