Open JCKodel opened 1 year ago
It sounds like your problem could easily be solved by making Failure
a sealed class and using a switch statement. But, if you don't want to do that, you could add an abstract method to Failure
, which would require all implementing classes to override said method.
abstract class Failure {
String getFailureMessage();
...
}
class NumberOutOfRangeFailure extends Failure {
final int minValue = ...; // Get these values however you want
final int maxValue = ...;
@override
String getFailureMessage() {
return "Number should be between ${minValue} and ${maxValue}";
}
}
Then you can just use any instance of a subclass of Failure
to call getFailureMessage()
.
Scenario:
Either<Failure, Success>
.Failure
is a base class for "I don't have a clue what happened"I can extend
Failure
to be more precise, for instance:const Left(NumberOutOfRangeFailure(minValue: 1, maxValue: 99))
, meaning: you can only chose between numbers 1 and 99Failure
class, without usingif
orswitch
?What about:
In the above code, I just ignore the
Success
(right), because, well, I don't need to inform the user about it, but forFailure
(left), I can test it using generics and have typed failures to create my error message string (notice how I interpolate the minValue and maxValue in the error message).How?
Using this code (based on #48):
So now I can filter my result (by
bool
predicate), or I can match types using mywhen
extension.Anyway, my feature request is to incorporate that
when
,on
andotherwise
intoEither<L, R>
.