gpt4 book ai didi

scala - 为什么是 List[T] 而不是 List[Int]? T是什么意思?

转载 作者:行者123 更新时间:2023-12-04 16:48:42 25 4
gpt4 key购买 nike

在我准备好的所有示例中,这种函数定义不断出现:

def firstElementInList[T](l: List[T]): T

看惯了 List[Int]所以它将是一个整数列表。在这种情况下,我假设 T是任何类型(如果我错了,请纠正我)。我真正关注的是 [T]紧随其后 firstElementInList

最佳答案

这只是一种说明:这个函数引用了一个泛型类型 T (你是对的 T 是任何类型)。

如果在一个类中有多个方法:

def firstElementInList[T](l: List[T]): T = l.head
def lastElementInList[T](l: List[T]): T = l.last

那么每个方法都有自己的 T类型,因此您可以使用 String 列表调用第一个方法s 和第二个列表为 Int s。

然而,包含这两种方法的整个类也可以具有类型:
class Foo[T] {
def firstElementInList(l: List[T]): T = l.head
def lastElementInList(l: List[T]): T = l.last
}

在这种情况下,您在 Foo 期间选择类型对象创建:
val foo = new Foo[String]

并且编译器会阻止你调用 foo 的实例方法使用除 List[String] 以外的任何其他类型.另请注意,在这种情况下,您不再需要输入 [T]对于方法 - 它取自封闭类。

关于scala - 为什么是 List[T] 而不是 List[Int]? T是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8331620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com