modddels icon indicating copy to clipboard operation
modddels copied to clipboard

Default non-constant value for factory parameter

Open chikamichi opened this issue 1 year ago • 6 comments

Hi (again) 👋

I have this ValueObject implementing a [0.0; 1.0] double inclusive range:

import "package:freezed_annotation/freezed_annotation.dart";
import "package:modddels_annotation_fpdart/modddels_annotation_fpdart.dart";

part 'percentage.modddel.dart';
part 'percentage.freezed.dart';

@Modddel(
  validationSteps: [
    ValidationStep([Validation("range", FailureType<RangeFailure>())]),
  ],
)
class Percentage extends SingleValueObject<InvalidPercentage, ValidPercentage>
    with _$Percentage {
  Percentage._();

  factory Percentage(double value) {
    return _$Percentage._create(
      value: value,
    );
  }

  @override
  Option<RangeFailure> validateRange(percentage) {
    if (percentage.value < 0.0) {
      return some(const RangeFailure.min());
    }
    if (percentage.value > 1.0) {
      return some(const RangeFailure.max());
    }
    return none();
  }
}

@freezed
class RangeFailure extends ValueFailure with _$RangeFailure {
  const factory RangeFailure.min() = _Min;
  const factory RangeFailure.max() = _Max;
}

Which is leveraged in this kind of modddel factories:

class MapLayer extends SimpleEntity<InvalidMapLayer, ValidMapLayer>
    with _$MapLayer {
  MapLayer._();

  factory MapLayer.raster(
      {required MapLayerPosition position,
      required URI uri,
      @validParam bool loaded = false,
      @validParam bool enabled = false,
      Percentage opacity = 1.0}) {
    return _$MapLayer._createRaster(
      position: position,
      uri: uri,
      loaded: loaded,
      enabled: enabled,
      opacity: opacity,
    );
  }

  // etc.
}

The opacity attribute has an error: A value of type 'double' can’t be assigned to a variable of type 'Percentage'.

Should I somehow use Percentage(1.0) instead of the 1.0 literal? In which case I get the (expected) following error: The default value of an optional parameter must be constant.

chikamichi avatar May 31 '23 14:05 chikamichi