您是否曾被 OO 语言文档中的 <E>、<T>、<K、V> 难住?
在 Reddit 的/r/dartlang群组里,一位名叫NFC_TagsForDroid的用户联系了我,询问我关于 Dart 文档的一些困惑。具体来说,是想了解演示代码示例时使用的一些“token”的含义。
以下是用户评论的摘录:
你能写一篇关于如何阅读 Dartlang 文档的解释吗?大部分内容对初学者来说毫无意义。例如:https://api.dartlang.org/stable/2.1.0/dart-core/List/add.html (Dart dart:core List<E> 添加抽象方法)
标题 List<E> 添加抽象方法<E> 是什么?它作为抽象方法有什么影响?
用户指的是 List 类型add()
方法的签名:
void add(
E value
);
造成混淆的根源是E
。其他在各种文档代码示例中使用的还有T
、K
和V
。
那么这些意味着什么?
这些看似神奇的“标记字母”实际上是占位符,用来表示所谓的类型参数。这在静态类型的面向对象语言中很常见,在泛型中会更加明显。
泛型提供了一种告诉编译器正在使用什么类型的方法,以便它知道要检查该类型。
换句话说,如果您将<E>
其读作“of Type ”,那么它将List<String>
被读作“List of String ”。
现在看一下,假设我们定义一个List<E>
:
List<String> fruits = ['apple', 'orange', 'pineapple'];
再次查看 add 方法:
void add(
E value
);
理解这一点的方法是,代表集合中的E
一个元素,无论我们最初创建该列表时指定的类型是什么!就fruits
其而言String
。
我们的使用方法如下:
fruits.add('mango');
fruits.add(1); // This will throw an error as it's the wrong type
那么为什么要使用特定的字母呢?
最简单的答案是约定。实际上,你可以使用任何你喜欢的字母,达到同样的效果。然而,常见的字母带有语义含义:
T
是一种类型E
是一个元素(List<E>
:元素列表)K
是关键(在Map<K, V>
)V
是值(作为返回值或映射值)
即使我不使用上述任何占位符,下面的代码也能正常工作。例如,请看下面的代码片段:
class CacheItem<A> { // Using the letter A
CacheItem(A this.itemToCache);
final itemToCache;
String get detail => '''
Cached item: $itemToCache
The item type is $A
''';
}
void main() {
var cached = CacheItem<int>(1);
print(cached.detail);
// Output:
// Cached item: 1
// The item's type is int
}
尽管使用的占位符是 ,但这种方法仍然有效A
。按照惯例T
,应该使用:
class CacheItem<T> {
CacheItem(T this.itemToCache);
final itemToCache;
String get detail => '''
Cached item: $itemToCache
The item type is $T
''';
}
泛型的强大之处在于它允许我们重复使用具有各种类型的同一个类:
CacheItem<String> cachedString = CacheItem<String>('Hello, World!');
print(cachedString.detail);
// Output:
// Cached item: Hello, World!
// The item's type is String
var cachedInt = CacheItem<int>(30);
print(cachedInt.detail);
// Output:
// Cached item: 30
// The item's type is int
var cachedBool = CacheItem<bool>(true);
print(cachedBool.detail);
// Output:
// Cached item: true
// The item's type is bool
我希望这篇文章能给你带来启发,并且让你学到一些新东西。
进一步阅读
分享就是关爱🤗
如果您喜欢这篇文章,请通过各种社交媒体渠道分享。此外,欢迎关注我的 YouTube 频道(点击小铃铛图标),观看 Dart 相关视频。
订阅我的电子邮件通讯即可免费下载我的 35 页《开始使用 Dart》电子书,并在发布新内容时收到通知。
喜欢、分享并关注我😍以获取有关 Dart 的更多内容。
鏂囩珷鏉ユ簮锛�https://dev.to/creativ_bracket/ever-been-stumped-by-etkv-in-oo-language-documentation-4hg4