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?
CodePudding user response:
Unfortunately, Dart doesn't support this. However, you could use extension methods to do something similar.
With Extension Methods
extension StringX on String {
/// Used to do something on an `int` like this:
///
/// ### Example
/// 'SomeString'.myFunction()
///
String myFunction() {
// directly call any function you would normally call on a string
// Below is the same as calling `this.substring...`
return substring(0, 1).toUpperCase() substring(1);
}
}
extension IntX on int {
/// Used to do something on an `int` like this:
///
/// ### Example
/// 42.myFunction()
///
SomeType myFunction() {
return this *
4; // `this` is a reference to the int this method was called on
}
}
CodePudding user response:
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.