Issue
Suppose I decorate a function like this so:
SomeType myFuntion( int x ) {
. . .
}
Suppose, I'd like to make it polymorph and accept an int or a String
as parameter x
.
In this case I may declare x
as dynamic
. Unfortunately, the function shouldn't be that dynamic
. It should not accept any typed value.
Q: May I somehow declare ( int | String )
as type alternatives?
Solution
You could also use Functional Programming with the help of the Dartz package.
import 'package:dartz/dartz.dart';
Either<int, String> doSomething(bool flag) {
return flag ? Left(123) : Right("One Two Three");
}
void main() {
final flags = [true, false];
flags.map((flag) => doSomething(flag).fold(
(myNum) => print('Got the number $myNum'),
(myStr) => print('Got the string "$myStr"')));
}
Added benefit of this solution: you know which type (Left or Right) you get back from your function.
Answered By - Thierry
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.