Type inference in Dart

15 views
Skip to first unread message

dop...@gmail.com

unread,
Aug 8, 2018, 12:53:43 PM8/8/18
to Dart Core Development

In Swift, when the type of a value can be inferred, you can omit it.


E.g.


 if (animation.status == AnimationStatus.finished || 

     animation.status == AnimationStatus.dismissed) {
 
} 


becomes


If (animation.status == .finished || 

    animation.status == .dismissed) {

 

}


How come we don’t have this in Dart too?

Is it being worked on for Dart 3.0 maybe?

Bob Nystrom

unread,
Aug 8, 2018, 1:46:11 PM8/8/18
to dop...@gmail.com, Dart Core Development
On Wed, Aug 8, 2018 at 12:44 AM, <dop...@gmail.com> wrote:

In Swift, when the type of a value can be inferred, you can omit it.

E.g.

 if (animation.status == AnimationStatus.finished || 

     animation.status == AnimationStatus.dismissed) {
 
} 

becomes

If (animation.status == .finished || 

    animation.status == .dismissed) {

 

}

This is not what people usually refer to when they talk about "type inference". :)

But, yes, this is a nice feature. We have discussed it some for Dart, especially recently. It's more difficult in Dart because Dart enums are not as powerful as enums in other languages. (For example, Swift enums have associated values. Java enums can have methods and field.) Because Dart enums are limited, users often define enum-like classes instead:

class Color {
  static const red = Color(255, 0, 0);
  static const green = Color(0, 255, 0);
  static const blue = Color(0, 0, 255);

  final int r, g, b;
  const Color(this.r, this.g, this.b);
}

 This is basically the old Java "type-safe enum pattern" from back before Java had enums. The pattern is still common in Dart.

Today, it's fairly common for users to initially define an enum and then later turn it into a class when they discover it needs more functionality. This is usually a safe change.

If we were to do some kind of ".red" shorthand syntax that only applies to enums then (1) it wouldn't be very useful and (2) it means turning an enum into a class becomes a breaking API change.

So if we do this, we probably need to think about either making enums more powerful, or being able to apply the syntax to non-enum use cases. Either of those make this a more complex change. Still worth considering of course, but it has to be prioritized relative to all of the other changes we want to make too.

Cheers!

– bob

Reply all
Reply to author
Forward
0 new messages