Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why main() return value does not set exitcode in dart?

Tags:

dart

Dart is suppose to be pragmatic, intuitive, etc. I wonder Why top-level main() does not set exitcode if int is returned?

I know, you can set it via dart:io.exitCode= or use dart:io.exit().

The question is why language designers decided to drop such popular convention?

#!/path/to/dart --checked
int main() {
  int myExitCode = 5;
  return myExitCode;
}

It returns 0 (as described in documentation), but in command-line world it's just silly. It does not even warn you (compiler checked mode, dartanalyzer). Script just silently return 0. Is there any rationale behind it?

UPDATE:

proposal bug: https://code.google.com/p/dart/issues/detail?id=21639

like image 827
Michał Šrajer Avatar asked Nov 17 '14 15:11

Michał Šrajer


2 Answers

The main() method in Dart always returns void, even if you specify otherwise. See The main() function As mentioned in the answer from John Evans, you must use the exit function if you want to return a value. This is because the Dart VM runs in both CLI and in a browser. It makes no sense in terms of the browser to provide a return value from main(). Thus the functionality is limited to the dart:io library which will only run in the CLI version of the dart VM.

like image 178
Matt B Avatar answered Oct 28 '22 05:10

Matt B


My understanding for this is that while main() may finish executing, you might have other asynchronous work going on that hasn't completed yet. You can use exit from the dart:io lib to return a exit code immediately.

import 'dart:io';

 main(){
    exit(42);
 }

More info from the API docs about exit: https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart:io#id_exit

like image 44
John Evans Avatar answered Oct 28 '22 06:10

John Evans