简体   繁体   中英

class parameter or class identifier query

I am new in Dart and works on an app that has a class look like this:

abstract class BaseUseCase <In,Out> {} 

My question is then, what is In and Out ?

In and Out are type arguments . They are used to allow the code in the class to use objects of an unknown type while remaining consistent and type-safe.

For example, say you wanted to have a method in a class that would take a list of any type, perform a string conversion operation on every element, and then return a strongly typed map of results:

class Stringifier<T> {
  Map<T, String> stringify(List<T> input) =>
      {for (final entry in input) entry: input.toString()};
}

void main() {
  Stringifier<int>().stringify([1, 2, 3]);
  // Result: <int, String>{1: '1', 2: '2', 3: '3'}
}

Note that the return type and input argument type use the generic T type. This ensures that only a list of the given type can be passed in, and that the resultant map will have the correct key type.

Type arguments can be used in other declarations as well, such as function declarations - indeed, the example above can be simplified, and declared outside a class:

Map<T, String> stringify(List<T> input) { /* ... */ }

More information on generics can be found in the Dart Language Tour , as well as in the "Generics" section of the Dart 2 language specification .

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