```sealed class Error(val code: String) { obje...
# getting-started
a
Copy code
sealed class Error(val code: String) {
    object Type1 : Error("type1")
    data class Type2(val someParam: String) : Error("type2")
}

// somewhere else in code
if (error.code == Type2.code) { }
Is there a best practice for achieving a check like above with a data class sealed class?
r
you don't really need the
code
really since you can do the check with
is
eg, either
error is Error.Type2
or do it with when
Copy code
when(error) {
    is Error.Type1 -> {}
    is Error.Type2 -> {}
}
1
m
if (error is Type2)
?
r
ye
a
Ah right. I think the example is incorrect. Suppose the code is a raw value from an API?
actually the
error
in
error.code
is of different type
m
the code is
val
, so it won't be other than
"type2"
in your example
a
and I’m trying to map it
m
if it were varying, than you'd have to check the code as you suggested
a
My code won’t compile since Type2 is a data class. I supposed I could do
if (error.code == Type2("").code)
but it looks hacky
r
what are you trying to figure out about the error?
m
Do you mean the
error
isn't an instance of
Error
?
a
yes, think like a generic
SomeApiError
m
OK, then you'd be better of by simply extracting the "type2" into a string constant and reusing both in the sealed class and in your some API error
a
I see, yeah, that’s probably it. like separate const vals for the codes itself