t
Hi
Im investigating the use of
when
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
?
h
You can't extend
when
statements, but you can of course create a method in the superclass to call from any subclass.
t
yes, I was just "Painting a picture with words" 🎨 😄
however I was looking for an approach where I achived the "standard"
is
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()
r
This would be one way:
Copy code
sealed 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()
  }
}
But you might want to think about whether you should just make a separate abstract method on the superclass for each time you want to do this
when
.
j
I thought it was bad practice to have an
else
clause in a
when
when going over sealed classes
r
Probably better not to - just list all the remaining as the final case. Then the compiler will force you to think about it if you add a new subtype, rather than it just going in the else bucket.