I wonder if this can be done at all. Consider this...
# codingconventions
m
I wonder if this can be done at all. Consider this structure
Copy code
sealed 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).
e
add
Copy code
is SpecificFormError -> message() // this calls the SpecificFormError overload since it has been smart casted
to
GeneralFormError.message()
m
I could, but then GeneralFormError would have tk know about all of the specific error (there will be lots of them in different places)
e
if it's a sealed interface they must be enumerable
that has to be done either within this function or at all calllers
👍 1