From the course: Kotlin for Android: Best Practices
Unlock the full course today
Join today to access over 22,600 courses taught by industry experts or purchase this course individually.
Sealed classes - Kotlin Tutorial
From the course: Kotlin for Android: Best Practices
Sealed classes
- Lets take a look at this 'when' statement again. We have 2 cases. If it's one of the four corner states we know we return true. Else, we return false. If we remove the else case Kotlin complains that "'when' expression must be exhaustive, "add necessary 'else' branch". But sometimes we know all the cases we are going to ever see and we don't really need that 'else' branch. In that case, one thing you can use is a 'sealed' class. Lets take a look. Here I have a sealed class called 'Exercise' and right now I want to do 2 kinds of exercises. I either run or I go for yoga. I don't do anything else. By putting inside of a sealed class when I use it in a 'when' statement I don't need to define 'else'. So for example, here I have a function called 'needMat'. So depending on the type of exercise I may or may not need to bring my mat. You can see that when I say, when exercise is Exercise.run I return false and when it is yoga, I return true. Let me quickly run this. So in the function…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.