https://kotlinlang.org logo
#getting-started
Title
# getting-started
a

allan.conda

03/24/2021, 9:52 AM
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

Roukanken

03/24/2021, 9:56 AM
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

Mykola Gurov

03/24/2021, 9:57 AM
if (error is Type2)
?
r

Roukanken

03/24/2021, 9:57 AM
ye
a

allan.conda

03/24/2021, 9:57 AM
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

Mykola Gurov

03/24/2021, 9:58 AM
the code is
val
, so it won't be other than
"type2"
in your example
a

allan.conda

03/24/2021, 9:58 AM
and I’m trying to map it
m

Mykola Gurov

03/24/2021, 9:58 AM
if it were varying, than you'd have to check the code as you suggested
a

allan.conda

03/24/2021, 9:59 AM
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

Roukanken

03/24/2021, 10:00 AM
what are you trying to figure out about the error?
m

Mykola Gurov

03/24/2021, 10:00 AM
Do you mean the
error
isn't an instance of
Error
?
a

allan.conda

03/24/2021, 10:01 AM
yes, think like a generic
SomeApiError
m

Mykola Gurov

03/24/2021, 10:01 AM
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

allan.conda

03/24/2021, 10:02 AM
I see, yeah, that’s probably it. like separate const vals for the codes itself
5 Views