Home > Software engineering >  Can we use var as a return type of a function?
Can we use var as a return type of a function?

Time:04-06

Can we use var as the return type of a function in dart?

For example:

var add(var a,var b) => a b;

This snippet of code was producing an error for me and I had to replace the var with int.

CodePudding user response:

Normally when we talk about "var" in Dart it means that it can be an int, double, or even a String, here we use a dynamic, which returns any value (int, double, etc) referring to whatever is inside your function. But you have to be sure that it can return something dynamic, if it is a sum then you return int.

  dynamic add(dynamic a, dynamic b) => a b;

CodePudding user response:

replacing var with int is just declaring which type of variable a and b are.

CodePudding user response:

From documentation

var: A way to declare a variable without specifying its type. The type of this variable (int) is determined by its initial value (42).

If you want dynamic, you can remove return type or adding dynamic in this case.

dynamic add(var a, var b) => a   b;

or just

add(var a, var b) => a   b;
  • Related