Sudhir Singh Khanger

07/21/2021, 11:17 AM
var drivingStyle = when (getWeatherConditions()) {
   "Sunny" -> "Speedy"
   "Foggy", "Rainy" -> "Safely"
   "Blizzard" -> "Don't drive!"
   else -> "Undefined"
sealed class Weather
object Rainy : Weather()
object Sunny : Weather()
object Foggy : Weather()
object Blizzard : Weather()

var drivingStyle = when (getWeatherConditions()) {
   Sunny -> "Speedy"
   Foggy, Rainy  -> "Safely"
1. What is the benefit of using Sealed classes in this case over
? Is it expensive to create a Sealed class over a constant? The one benefit I see is that I don't have to add
branch if I use all classes of the Sealed class. 2. When a derived class of a Sealed class is used in a when block then does when know all the classes which extend a sealed class?


07/21/2021, 12:21 PM
1. The benefit is that the compiler will know if you handled all the cases. In this case I would use an enum over constant or a sealed class. I would guess that a sealed class and an enum have a bit more overhead than a constant, but it would be insignificant. 2. The point of a sealed class is so the compiler knows all the possible subtypes.

Alexis Manin

07/22/2021, 6:18 AM
In fact, using enum as suggested by @mkrussel would be more optimized, because their equality test is far faster than String one (it is basically a single integer comparison, that is called "ordinal"). As for sealed classes, they're useful when you want to model a state over a constant concept. For example, you could transform blizzard like so :
data class Blizzard(val windSpeed) : Weather
By state, I do not mean like enums. I mean that you can create two different Blizzard object with a different windSpeed. It allows to create "frozen" type hierarchy, but does not have the restriction over instances (except if you use
like in your example).

Sudhir Singh Khanger

07/22/2021, 6:13 PM
Thanks for the clarification.