Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the default return value of a Dart function?

Tags:

return

dart

The function below works even though I intentionally deleted 'return' command:

main() {
  add(i) => i + 2; //I intentionally deleted 'return'
  print(add(3)); //5
}

But, the function below doesn't work after I intentionally deleted the 'return' command.

main() {
makeAdder(num addBy) {
 return (num i) {
    addBy + i; //I intentionally deleted 'return'
  }; 
}

 var add2 = makeAdder(2); 
  print(add2(3) ); //expected 5, but null.
}

Edited to clarify my question.

The last sentence in the latter function above, add2(3) doesn't return a value(I expect 5) but just null returns.

My question is why 'addBy + i' of the latter function doesn't return contrary to the fact that 'add(i) => i + 2' of the first function returns 'i + 2'.

Edited again. The answer is in the fact of '=>' being {return }, not just {}.

main() {
makeAdder(num addBy) => (num i) { return addBy + i; }; 


 var add2 = makeAdder(2); 
  print(add2(3) ); // 5
}

Even the code below works as '=>' has 'return' command in it.

main() {
makeAdder(num addBy) => (num i) => addBy + i; ; 


 var add2 = makeAdder(2); 
  print(add2(3) ); //5
} 
like image 834
Letsgo Avatar asked Sep 09 '14 05:09

Letsgo


2 Answers

In Dart each function without an explicit return someValue; returns null;

The null object does not have a method 'call'.

makeAdder (add2) without return returns null and null(3) leads to the exception.

like image 163
Günter Zöchbauer Avatar answered Sep 25 '22 09:09

Günter Zöchbauer


I would like to quote two important note here. It might help others:

  1. Though Dart is Optionally typed ( meaning, specifying the return type of a function such as int or void is optional ), it always recommended to specify type wherever possible. In your code, as a sign of good programming practice, do mention the return type.

  2. If your function does not return a value then specify void. If you omit the return type then it will by default return null.

    All functions return a value. If no return value is specified, the statement return null; is implicitly appended to the function body.

like image 41
Sriyank Siddhartha Avatar answered Sep 24 '22 09:09

Sriyank Siddhartha