首页 文章

在Dart中调用泛型函数(2.0.0-dev.62.0)

提问于
浏览
1

为什么以下代码甚至编译(Dart VM版本: 2.0.0-dev.62.0 ):

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

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

我以为 f<A>(..) 选择 fA 版本?

1 回答

  • 3

    默认情况下,Dart VM在默认情况下(默认情况下通过Flutter和is coming soon for Dart v2 dev)不使用Dart 2语义,因此您需要使用 --preview-dart-2 运行 . 如果你这样做,你会收到一个错误:

    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"));
    

相关问题