But isn’t that the point of sealed classes? That t...
# announcements
m
But isn’t that the point of sealed classes? That they act like enums and help you perform pattern-matching, without the need of the
else
branch?
p
No,
sealed class
restricts class hierarchy, i.e. all direct sub-classes are known at compile type. So you can have exhausted
when
on class type, while you can create as much objects as you want and all of them can be different.
k
Ah are you saying
is X
checks are failing?
m
@karelpeeters Yep, the sealed class child received via intent extras doesn’t match any of the sealed class children.
@Pavlo Liapota So, how would the pattern matching work? If two objects of the same sealed class’ sub-class are different, how does
when
match them?
p
You said that hashcodes were different so I assumed that you were comparing objects and not their type.
☝️ 1
So what happens at runtime? Do you have
when
as expression over all subtypes of sealed class and no branches are executed? Do you get runtime exception?
m
@Pavlo Liapota no runtime exception.
when
doesn’t execute any branch.
p
Interesting, I guess you are using
when
as statement, but what will happen if you use it as expression? So something should be returned by a
when
from one branch.
m
@Pavlo Liapota ah, let me check.
@Pavlo Liapota Got a
NoWhenBranchMatchedException
exception here.
p
And what is a type of that object?
g
This may happen if you compare an object by equal, not type
And serialization created new instance of singleton using reflections
Pleasе, show your code of
when
m
@gildor Yes, using serializable, it works if I use
is Type
in
when
, but not if I match directly
When using
Parcelable
, it works normally, as expected, but with
Serializable
, I have to match by type. Could you explain why this happens?
g
Yes, this is exactly what other people suggested in this thread. Use
is Type
or implement serialization properly
To avoid creation object instance
Because serialization is bad dangerous API that not recommended to use 🤷
m
oh, this is news to me. Is Parcelable better?
g
It creates new instance of object using reflections
You can avoid it if implement serialization manually
Parcelable doesn't try to use any runtime reflection magic, you always implement it manually
p
Hm, I didn’t know you can have exhaustive
when
over instances if all children are
object
.
Or more precisely I knew, but never thought of it 🙂
m
@gildor yes, I’m using the Parcelize annotation so I guess that’s doing all the heavy work for me here.
g
Yes, if you use can parcelize use it instead of serializable
@Pavlo Liapota If all sealed classes are objects it means that you should probably choose enums instead of sealed classes.