Tower Guidev2
08/04/2021, 2:40 PMTower Guidev2
08/04/2021, 2:40 PMwhen
I have a sealed class of values and want to identify each case as shown below
*when*(x) {
*is* SealedInitial -> doNothing()
*is* SealedOne -> something(x.value)
*is* SealedTwo -> somethingElse(x.value)
*else* -> doNothing()
}
I have to perform this test "All Over" my application, however the only constant check I will always need is
the first one, e.g. *is* SealedInitial -> doNothing()
I would like to have thi scase handled by a super class so that all my Sub Classes do not need to keep coding that line
Is this possible? To have a when
statement "extend" a super when
?hho
08/04/2021, 2:50 PMwhen
statements, but you can of course create a method in the superclass to call from any subclass.Tower Guidev2
08/04/2021, 2:54 PMTower Guidev2
08/04/2021, 2:56 PMis
case fro free,
e.g. if I have to write a line to always call the super class method, I might as well stick to always coding the *is* SealedInitial -> doNothing()
Rob Elliot
08/04/2021, 3:05 PMsealed class SealedSuper {
open fun doWork(work: () -> Unit) = work()
}
class SealedInitial : SealedSuper() {
override fun doWork(work: () -> Unit) {
doNothing()
}
}
x.doWork {
when (x) {
is SealedOne -> something(x.value)
is SealedTwo -> somethingElse(x.value)
else -> doNothing()
}
}
Rob Elliot
08/04/2021, 3:09 PMwhen
.Jilles Soeters
08/04/2021, 4:56 PMelse
clause in a when
when going over sealed classesRob Elliot
08/05/2021, 8:41 AM