Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Dart's Strong-Mode, can I leave off types from function definitions?

Tags:

dart

For example, I'd like to just be able to write:

class Dog {
  final String name;

  Dog(this.name);

  bark() => 'Woof woof said $name';
}

But have #Dog.bark's type definition be () => String.

This previously wasn't possible in Dart 1.x, but I'm hoping type inference can save the day and avoid having to type trivial functions where the return type is inferable (the same as it does for closures today?)

like image 597
matanlurey Avatar asked Feb 02 '17 21:02

matanlurey


1 Answers

The language team doesn't currently have any plans to do inference on member return types based on their bodies. There are definitely cases like this where it would be nice, but there are other cases (like recursive methods) where it doesn't work.

With inference, we have to balance a few opposing forces:

  1. Having smart inference that handles lots of different cases to alleviate as much typing pain as we can.

  2. Having some explicit type annotations so that things like API boundaries are well-defined. If you change a method body and that changes the inferred return type, now you've made a potentially breaking change to your API.

  3. Having a simple boundary between code that is inferred and code that is not so that users can easily reason about which parts of their code are type safe and which need more attention.

The case you bring up is right at the intersection of those. Personally, I lean towards not inferring. I like my class APIs to be pretty explicitly typed anyway, since I find it makes them easier to read and maintain.

Keep in mind that there are similar cases where inference does come into play:

  • Dart will infer the return type of an anonymous function based on its body. That makes things like lambdas passed to map() do what you want.

  • It will infer the return type of a method override from the method it is overriding. You don't need to annotate the return type in Beagle.bark() here:

    class Dog {
      String bark() => "Bark!";
    }
    
    class Beagle extends Dog {
      final String name;
    
      Dog(this.name);
    
      bark() => 'Woof woof said $name';
    }
    
like image 192
munificent Avatar answered Oct 07 '22 02:10

munificent