Home > Back-end >  Where does additional value comes from in Dart code?
Where does additional value comes from in Dart code?

Time:12-06

The following code produces two values as output. It's clear why it prints in func. But where does the 2nd value come from (null)?

func(){
  print("in func");
}

void main() {
  var x = func;
 
  print(x());
  
}

Output:

in func
null 

CodePudding user response:

You treated Dart like a scripting language and as a result, you got puzzled. Treat Dart as a the real programming language it is and it will be crystal clear:

dynamic func() { 
// ^-- "dynamic" was inserted by your compiler,
// to make up for the fact you failed to mention a return type

  print("in func");

  // this is inserted by your compiler, to make up for the
  // fact that a non-void function failed to provide a return value:
  return null;
}

void main() {
  var x = func;
 
  // so this first calls the function, which prints it's line
  // and then it prints the functions return value, which is null.
  print(x());
}

Be explicit when programming. Use the power this language gives you.

When in doubt, turn on analysis. It will tell you what I told you: you missed to explicitely state things and now the compiler has to cover for you. That makes it hard to see what actually happens. Don't be hard on future readers. One of them is you, 5 seconds from now. Make it easy for yourself and be explicit about what code is doing.

  • Related