RandomStudent
RandomStudent

Reputation: 427

Calling generic functions in Dart (2.0.0-dev.62.0)

Why does the following code even compile (Dart VM version: 2.0.0-dev.62.0):

int f<T>(T q) {
       return q.hashCode;
}       

void main() {
        print(f<int>(23));
        print(f<int>("wow"));
}    

I thought f<A>(..) selects the A version of f?

Upvotes: 1

Views: 53

Answers (1)

Danny Tuppeny
Danny Tuppeny

Reputation: 42333

The Dart VM does not use Dart 2 semantics by default when invoked directly yet (it does via Flutter, and is coming soon for Dart v2 dev), so you need to run with --preview-dart-2. If you do, you'll get an error:

Dannys-MacBook:lib danny$ dart --preview-dart-2 test.dart
test.dart:7:22: Error: A value of type 'dart.core::String' can't be assigned to a variable of type 'dart.core::int'.
Try changing the type of the left hand side, or casting the right hand side to 'dart.core::int'.
        print(f<int>("wow"));

Upvotes: 3

Related Questions