简体   繁体   中英

What does "< >" mean in Dart?

Through an online Dart course, I've found some values bracketed with "less than" and "greater than" marks such as"List< E >" .

eg

List<int> fixedLengthList = new List(5);

I couldn't find a direct answer online, probably because that question was too basic. Could someone explain what those marks exactly indicate? Or any links if possible.

This are generic type parameters. It allows specializations of classes.

List is a list that can contain any value (if no type parameter is passed dynamic is used by default). List<int> is a list that only allows integer values and null`.

You can add such Type parameters to your custom classes as well.
Usually single upper-case letters are used for type parameter names like T , U , K but they can be other names like TKey ...

class MyClass<T> {
  T value;
  MyClass(this.value);
}

main() {
  var mcInt = MyClass<int>(5);
  var mcString = MyClass<String>('foo');
  var mcStringError = MyClass<String>(5); // causes error because `5` is an invalid value when `T` is `String`
}

See alsohttps://www.dartlang.org/guides/language/language-tour#generics

例如,如果你打算让一个列表只包含字符串,你可以将它声明为List<String> (读作“字符串列表”)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM