'Declaring multiple alternative types instead of dynamic
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 1:[1]
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
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | SupposedlySam |
