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

Tower Guidev2

08/04/2021, 2:40 PM
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

hho

08/04/2021, 2:50 PM
You can't extend
when
statements, but you can of course create a method in the superclass to call from any subclass.
t

Tower Guidev2

08/04/2021, 2:54 PM
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

Rob Elliot

08/04/2021, 3:05 PM
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

Jilles Soeters

08/04/2021, 4:56 PM
I thought it was bad practice to have an
else
clause in a
when
when going over sealed classes
r

Rob Elliot

08/05/2021, 8:41 AM
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.