Is there an easier (and cleaner) way to pass an optional parameter from one function to another than doing this:
void optional1({num x, num y}) {
if (?x && ?y) {
optional2(x: x, y: y);
} else if (?x) {
optional2(x: x);
} else if (?y) {
optional2(y: y);
} else {
optional2();
}
}
void optional2({num x : 1, num y : 1}) {
...
}
The one I actually want to call is:
void drawImage(canvas_OR_image_OR_video, num sx_OR_x, num sy_OR_y, [num sw_OR_width, num height_OR_sh, num dx, num dy, num dw, num dh])
At least I don't get a combinatorial explosion for positional optional parameters but I'd still like to have something simpler than lot's of if-else.
I have some code that uses the solution proposed in the first answer (propagating default values of named optional parameters, but I lose the ability to check whether or not the value was provided by the initial caller).
I've been burned by this corner of Dart several times. My current guidelines, which I encourage anyone to adopt are:
Do not use default values. Instead, use the implicit default of null and check for that in the body of the function. Document what value will be used if null is passed.
Do not use the ? argument test operator. Instead, just test for null.
This makes not passing an argument and explicitly passing null exactly equivalent, which means you can always forward by explicitly passing an argument.
So the above would become:
void optional1({num x, num y}) {
optional2(x: x, y: y);
}
/// [x] and [y] default to `1` if not passed.
void optional2({num x, num y}) {
if (x == null) x = 1;
if (y == null) y = 1;
...
}
I think this pattern is cleaner and easier to maintain that using default values and avoids the nasty combinatorial explosion when you need forward. It also avoids duplicating default values when you override a method or implement an interface with optional parameters.
However, there is one corner of the Dart world where this doesn't work: the DOM. The ? operator was designed specifically to address the fact that there are some JavaScript DOM methods where passing null is different from passing undefined (i.e. not passing anything).
If you're trying to forward to a DOM method in Dart that internally uses ? then you will have to deal with the combinatorial explosion. I personally hope we can just fix those APIs.
But if you're just writing your own Dart code, I really encourage you to avoid default values and ? entirely. Your users will thank you for it.
Would positional paremeters be an option four your case?
void optional([num x = 1, num y = 1]) {
}
Since you call optional2 with default parameters anyway, this seems like a good replacement without knowing, what the purpose of the function is
Related
Consider the following Dart code:
class Vec2 {
num x, y;
Vec2(this.x, this.y);
Vec2 operator*(num rhs) => Vec2(x * rhs, y * rhs);
String toString() => "<$x, $y>";
}
void main() => print(Vec2(1, 2) * 3);
The output is as expected:
<3, 6>
However, this only works when the left-hand side of the expression is a Vec2 and the right-hand side is a num. In this case, I want the multiplication operator to be commutative, so I write the following extension:
extension Vec2Util on num {
Vec2 operator*(Vec2 rhs) => Vec2(rhs.x * this, rhs.y * this);
}
One might naturally expect the following code to produce identical output to the first snippet:
void main() {
num x = 3;
print("${x * Vec2(1, 2)}");
}
However, the compiler is instead reporting that The argument type 'Vec2' can't be assigned to the parameter type 'num'. It looks as though the compiler is resolving the multiplication to num operator*(num rhs) in this case and then complaining that my Vec2 can't be passed in as a num operand. Why does the compiler apparently disregard my extension? What is the correct way to create custom commutative operators like this?
You cannot do what you want.
Dart user-definable binary operators are all methods on the first operand. Doing e1 + e2 is kind-of like doing e1.+(e2) where + is the name of the method, except you can't normally call a method +.
In order to be able to do 3 * vector, you need the method to be on 3.
You can't add methods to other people's classes, not without fiddling with their source code, and int is a system class so even that is not possible.
You cannot use extension methods because extension methods do not apply when the receiver type already has an instance method with the same name.
And int defines all the operators.
(It's like, and definitely not coincidentally, that the user-definable operators were chosen from exactly what int needs. That's not new in Dart, the operators go back to C and Java.)
So, you can define an extension method on int, but you can't call it anyway, not without an override:
extension MyInt on int {
Vector operator *(Vector other) => other.scalerMultiplication(this);
}
... MyInt(3) * vector ...
That's more complication than just swapping the operands.
class X extends Y {
X(int a, int b) : super(a,b);
}
Can someone give me an explanation about the syntax meaning of the colon :?
This feature in Dart is called "initializer list".
It allows you to initialize fields of your class, make assertions and call the super constructor.
This means that it is not the same as the constructor body. As I said, you can only initialize variables and only access static members. You cannot call any (non-static) methods.
The benefit is that you can also initialize final variables, which you cannot do in the constructor body. You also have access to all parameters that are passed to the constructor, which you do not have when initializing the parameters directly in the parentheses.
Additionally, you can use class fields on the left-hand of an assignment with the same name as a parameter on the right-hand side that refers to a parameter. Dart will automatically use the class field on the left-hand side.
Here is an example:
class X {
final int number;
X(number) : number = number ?? 0;
}
The code above assigns the parameter named number to the final field this.number if it is non-null and otherwise it assigns 0. This means that the left-hand number of the assignment actually refers to this.number. Now, you can even make an assertion that will never fail (and is redundant because of that, but I want to explain how everything works together):
class X {
final int number;
X(number): number = number ?? 0, assert(number != null);
}
Learn more.
It's ok to access non static member in initializer list.
class Point {
num x, y;
Point(this.x, this.y);
Point.origin(): this.x = 10, this.y = 10;
}
main() {
Point p = Point.origin();
print(p.x); // 10
}
I am new to Dart and I can see Dart has num which is the superclass of int and double (and only those two, since it's a compile time error to subclass num to anything else).
So far I can't see any benefits of using num instead of int or double, are there any cases where num is better or even recommended? Or is it just to avoid thinking about the type of the number so the compiler will decide if the number is an int or a double for us?
One benefit for example
before Dart 2.1 :
suppose you need to define a double var like,
double x ;
if you define your x to be a double, when you assign it to its value, you have to specify it say for example 9.876.
x = 9.876;
so far so good.
Now you need to assign it a value like say 9
you can't code it like this
x = 9; //this will be error before dart 2.1
so you need to code it like
x = 9.0;
but if you define x as num
you can use
x = 9.0;
and
x = 9;
so it is a convenient way to avoid these type mismatch errors between integer and double types in dart.
both will be valid.
this was a situation before Dart 2.1 but still can help explain the concept
check this may be related
Not sure if this is useful to anyone, but I just ran into a case where I needed num in a way.
I defined a utility function like this:
T maximumByOrNull<T, K extends Comparable<K>>(Iterable<T> it, K key(T),) {
return it.isEmpty
? null
: it.reduce((a, b) => key(a).compareTo(key(b)) > 0 ? a : b);
}
And invoking it like this…
eldest = maximumByOrNull(students, (s) => s.age);
… caused trouble when age is an int, because int itself does not implement Comparable<int>.
So Dart cannot infer the type K in the invocation to maximumByOrNull.
However, num does implement Comparable<num>. And if I specified:
eldest = maximumByOrNull(students, (s) => s.age as num); // this
eldest = maximumByOrNull<Student, num>(students, (s) => s.age); // or this
the complaint went away.
Bottom line: it seems num implements Comparable when int and double do not, themselves, and sometimes this causes trouble for generic functions.
A good use case of num are extensions that work with int and double.
As an example I include the extension MinMax on List<num> that provides the getters min and max.
extension MinMax on List<num>{
/// Returns the maximum value or `null` if the list is empty.
num get max {
return (isNotEmpty)
? fold<num>(0, (prev, current) => (prev > current) ? prev : current)
: null;
}
/// Returns the minimum value or `null` if the list is empty.
num get min {
return (isNotEmpty)
? fold<num>(0, (prev, current) => (prev < current) ? prev : current)
: null;
}
}
Using the extension above one can access the min/max values without a need to create specific implementations for the classes int and double.
void main() {
final a = <int>[1,3,5];
final b = <double>[ 0.5, 0.8, -5.0];
print(a.min);
print(b.max);
}
I just ran into a use case when it is useful.
My app stores weight, which was originally defined as a double.
When using with a local database (sqlite) it works fine, since sqlite handles integer and real types.
However, when I converted my app to use Firestore database, I ran into issues with all my double fields. If a decimal value is stored everything works fine. However, when the weight happens to be a whole number, Firestore returns it as an int and suddenly type errors - int is not a subtype of type double - start to appear.
In the above scenario changing the double fields and variables to num was a quite simple solution.
Hello i have a created a function which accepts last argument as closure.
func sum(from: Int, to: Int, f: (Int) -> (Int)) -> Int {
var sum = 0
for i in from...to {
sum += f(i)
}
return sum
}
Now i when i call this function.One way to call this function is below like this .
sum(from: 1, to: 10) { (num) -> (Int) in
return 10
}
I have seen one of the concepts in swift as trailing closure.With trailing closure i can call the function like this .
sum(from: 1, to: 10) {
$0
}
but i don't know why it is able to call without any return statement.please tell me how it is happening ?
There really is no answer here except "because the language allows it." If you have a single expression in a closure, you may omit the return.
The section covering this is "Implicit Returns from Single-Expression Closures" from The Swift Programming Language.
Single-expression closures can implicitly return the result of their single expression by omitting the return keyword from their declaration, as in this version of the previous example:
reversedNames = names.sorted(by: { s1, s2 in s1 > s2 } )
Here, the function type of the sorted(by:) method’s argument makes it clear that a Bool value must be returned by the closure. Because the closure’s body contains a single expression (s1 > s2) that returns a Bool value, there is no ambiguity, and the return keyword can be omitted.
This has nothing to do with trailing closure syntax, however. All closures have implicit returns if they are single-expression.
As #rob-napier states, you can do it just because the language allows it.
But, note your example is also doing two different things in that last part:
sum(from: 1, to: 10) {
$0
}
Not only are you omitting the return statement, you're also omitting the named parameters, so the $0 is not dependant on the omitting the return feature.
This would be a more accurate example for just omitting return:
sum(from: 1, to: 10) { (num) -> (Int) in
num
}
That said, I wouldn't recommend using either of these features. In most cases, it's better to make the code easier to read later. Your future self (and others who use the code after you) will thank you.
The following code got compilation error:
var a : Int = 0
var b : Int = 3
var sum : Int = 0
while (sum = a+b) < 2 {
}
The error message is:
Cannot invoke '<' with an argument list of type '((()),
IntegerLiteralConvertible)'
How to solve this problem? (Of course I can put sum assignment statement out side the while statement. But this is not convenient. Any other advice? Thanks
In many other languages, including C and Objective-C, sum = a+b would return the value of sum, so it could be compared.
In Swift, this doesn't work. This was done intentionally to avoid a common programmer error. From The Swift Programming Language:
Swift supports most standard C operators and improves several capabilities to eliminate common coding errors. The assignment operator (=) does not return a value, to prevent it from being mistakenly used when the equal to operator (==) is intended.
Since the assignment operator does not return a value, it can't be compared with another value.
It is not possible to overload the default assignment operator (=), but you could create a new operator or overload one of the compound operators to add this functionality. However, this would be unintuitive to future readers of your code, so you may want to simply move the assignment to a separate line.
In most languages, assignments propagate their value -- that is, when you call
sum = a + b
the new value of sum is available for another part of the expression:
doubleSum = (sum = a + b) * 2
Swift doesn't work that way -- the value of sum isn't available after the assignment, so it can't be compared in your while statement. From Apple's documentation:
This feature prevents the assignment operator (=) from being used by
accident when the equal to operator (==) is actually intended. By
making if x = y invalid, Swift helps you to avoid these kinds of
errors in your code.
The other answers explain why your code won't compile. Here is how you can clean it up without calculating sum in the while loop (I'm assuming you want to be able to reassign what sum's getter is, elsewhere.):
var a = 0, b = 3
var getSum = { a + b }
var sum: Int { return getSum() }
while sum < 2 {
...and if you're okay with invoking sum with parentheses:
var a = 0, b = 3
var sum = { a + b }
while sum() < 2 {
You can rewrite it as a for loop, although you'll have to repeat the assignment and addition:
for sum = a+b; sum < 2; sum = a+b {
}