The Validate Methods

In unions of modddels, the validate methods also benefit from the shared properties feature and the case-modddels pattern matching.

Continuing with our Weather example (you can find it here), here is an example of an implementation of the validateHabitable method.

@override
Option<WeatherHabitableFailure> validateHabitable(weather) {
  // [temperature] is a shared property, so we can directly access it 
  // from [weather] :
  final temperature = weather.temperature;

  if (temperature > 60) {
    return some(const WeatherHabitableFailure.tooHot());
  }

  if (temperature < -10) {
    return some(const WeatherHabitableFailure.tooCold());
  }

  // You can use the case-modddels pattern matching methods on [weather] :
  return weather.maybeMapWeather(
    rainy: (rainy) => rainy.rainIntensity > 2.5
        ? some(const WeatherHabitableFailure.flooding())
        : none(),
    orElse: () => none(),
  );
}

In this implementation, the 'habitable' validation will fail under the following conditions :

  • No matter the weather kind (Sunny or Rainy) : If the temperature is more than 60 or less than -10, the validation fails

  • For the Rainy weather : If the rainIntensity is more than 2.5, the validation fails.

Last updated