Denis
02/17/2021, 6:28 PMsealed class A {
data class X(val m: Int) : A()
data class Y(val m: Int) : A()
data class Z(val m: Int) : A()
}
val x = when (val a: A = A.X(3)) {
is A.X, is A.Y -> a.m // <<<<<<<<<<
is A.Z -> a.m
}
1. Why does Android Studio say 'when' expression must be exhaustive, add necessary 'else' branch
? Aren't all cases covered here?
2. Why is a.m
no accessible on the marked line? It says Unresolved reference: m
.Denis
02/17/2021, 6:29 PMDenis
02/17/2021, 6:30 PMMarc Knaup
02/17/2021, 6:31 PMMarc Knaup
02/17/2021, 6:32 PMm
there because each class has their own m
property. That’s not supported.
If you want to access m
like that then add abstract val m: Int
to class A
and add override
in the subclasses.Denis
02/17/2021, 6:34 PMm
field.nanodeath
02/17/2021, 6:35 PMA.X
and A.Y
you should be able to access the m
field just fineDenis
02/17/2021, 6:36 PMnanodeath
02/17/2021, 6:37 PMDenis
02/17/2021, 6:40 PMnanodeath
02/17/2021, 6:42 PMm
, 2. pull m
up into A
itself, or 3. factor out the common logic into a method or callbackDenis
02/17/2021, 6:43 PMephemient
02/17/2021, 7:32 PMephemient
02/17/2021, 7:33 PMA
without m
, while all AWithM
subtypes have a common m
getterephemient
02/17/2021, 7:34 PMnanodeath
02/17/2021, 7:34 PMMarc Knaup
02/17/2021, 7:34 PMX
, Y
and Z
up into A
again so that you can use A.X
etc.ephemient
02/17/2021, 7:36 PMAWithM
inside a is X, is Y ->
branchMarc Knaup
02/17/2021, 7:37 PMis AWithM ->
Denis
02/17/2021, 7:47 PMwhen
. And before I got rid of m
-less class I tried the interface approach and ... it worked. Then I deleted the violating class and moved to abstract
field. Your suggestions were definitely useful, thanks folks!