java - 通用类型参数的 T、U、V 约定从何而来?

标签 java c# scala generics programming-languages

<分区>

Java、C# 和 TypeScript(又名 Sun/Hejlsberg 语言家族)使用 T , U , V等来表示泛型类型参数。表面上那是因为 T代表“类型”,UV关注T在字母表中。

另一方面,Scala 使用 A , B , C等等,OCaml 和 Haskell 使用 a , b , 和 c .

这些约定从何而来?是不是因为函数式语言更接近数学证明,其中 α , β , 和 γ按照惯例使用?


类似,但没有回答我的问题:Where does the C# generics naming convention come from? .

最佳答案

在标准的 Java SE API 中,设计者通常选择一个与类型参数的含义/用途相关的单字母标识符:

  • Iterator<T> - javadoc其中 T表示类型。其他例子是 ListIterator<T> , Iterable<T> , Comparable<T> , Comparator<T>Class<T> .
  • Collection<E> - javadoc其中 E指元素。各种其他集合类和接口(interface)使用 E .
  • Map<K,V> - javadoc其中 K表示 key ,V意味着值(value)。
  • Enum<E> - javadoc其中 E表示枚举。

这些往往会反驳您关于存在普遍(广泛)T 的断言。 , U , V约定,至少对于 Java。显然,在没有具体指导的情况下,一些个别设计师会采用什么是指导的明显扩展来使用T (见下面的链接)但这似乎是个人选择的结果。 (而且这些团体可能会认为这不值得讨论。)

(如果您想进行详尽搜索,请访问每个 javadocs 索引 A-Z 页面,并在其中搜索所有出现的“<”。)


I'm hoping for a link to an old discussion/commit/mailing list where the convention was first discussed.

对于 Java,我怀疑您会发现这一点。讨论和邮件列表本来是私有(private)的,当泛型被添加到语言中时,Java 源代码仍然关闭,以及上面的所有示例。


@Lew Bloch 找到了 T 的几个例子(见下文) , U , V在 Java 8 中作为流支持的一部分添加到 Java SE 的 API 中。我断言这并不能证明一个普遍的模式,大量预先存在的类反驳了它。

一般模式或惯例的其他负面证据:

最后,JLS ( JLS 6.1) 建议:

Type variable names should be pithy (single character if possible) yet evocative, and should not include lower case letters. This makes it easy to distinguish type parameters from ordinary classes and interfaces.

Container types should use the name E for their element type. Maps should use K for the type of their keys and V for the type of their values. The name X should be used for arbitrary exception types. We use T for type, whenever there is not anything more specific about the type to distinguish it. (This is often the case in generic methods.)

If there are multiple type parameters that denote arbitrary types, one should use letters that neighbor T in the alphabet, such as S. Alternately, it is acceptable to use numeric subscripts (e.g., T1, T2) to distinguish among the different type variables. In such cases, all the variables with the same prefix should be subscripted.

简而言之,UV JLS 中未明确提及,但其他替代方案是。

关于java - 通用类型参数的 T、U、V 约定从何而来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44589035/

相关文章:

java - 否则我该如何优化以下内容?

java - Hibernate继承和具有相同类的多个表

c# - 如何获取用户登录我的应用程序的机器帐户?

c# - 返回大数据时,AWS lambda 失败

斯卡拉。具有短语法的嵌套 lambda 的参数

java - 明智地打印树级别

Java for 循环与 while 循环。性能差异?

c# - 为什么即使没有其类的实例,成员常量也可用?

scala - 如何在 spark-ml CrossValidatorModel 中获得最佳逻辑回归的系数?

scala - Akka Streams 与 Akka HTTP 服务器和客户端