Case-modddels pattern matching

Let's continue with our Weather example (find it here).

The super-sealed classes have additional "special" pattern matching methods that allow you to map between the different modddels. In our example, these methods are : mapWeather, maybeMapWeather and mapOrNullWeather.

For Example :

weather.mapWeather(
  sunny: (Sunny sunny) {},
  rainy: (Rainy rainy) {},
);

weather.mapOrNullWeather(
  rainy: (Rainy rainy) {},
);

weather.maybeMapWeather(
  sunny: (Sunny sunny) {},
  orElse: () {},
);

In general, these methods are named 'map{ModddelName}', 'maybeMap{ModddelName}' and 'mapOrNull{ModddelName}'.

These methods can be used on all the super-sealed classes :

Super-sealed classCase-Modddels you can map between

Weather

Sunny - Rainy

ValidWeather

ValidSunny - ValidRainy

InvalidWeather

InvalidSunny - InvalidRainy

InvalidWeatherValue

InvalidSunnyValue - InvalidRainyValue

For Example :

weather.mapValidity(
  valid: (ValidWeather validWeather) {
    // Using `mapWeather` on `ValidWeather`
    validWeather.mapWeather(
      sunny: (ValidSunny validSunny) {},
      rainy: (ValidRainy validRainy) {},
    );
  },
  invalid: (InvalidWeather invalidWeather) {
    // Using `mapWeather` on `InvalidWeather`
    invalidWeather.mapWeather(
      sunny: (InvalidSunny invalidSunny) {},
      rainy: (InvalidRainy invalidRainy) {},
    );
  },
);

Notice how the type of the callback parameters changes according to which super-sealed class the mapWeather method is called on.

Last updated