在所有的例子我也准备这样的函数定义的不断弹出:为什么列出[T]而不是列表[Int]? T是什么意思?
def firstElementInList[T](l: List[T]): T
我已经习惯了看到List[Int]
所以这将是一个整数列表。在这种情况下,我假设T
是任何类型(请纠正我,如果我错了)。什么我真的被逮住的是[T]
之后firstElementInList
在所有的例子我也准备这样的函数定义的不断弹出:为什么列出[T]而不是列表[Int]? T是什么意思?
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
秒的列表,第二个与Int
列表秒。
但是全班围绕这两种方法可以有类型,以及:Foo
对象创建期间
class Foo[T] {
def firstElementInList(l: List[T]): T = l.head
def lastElementInList(l: List[T]): T = l.last
}
在这种情况下,你挑类型:
val foo = new Foo[String]
编译器会阻止你从foo
调用实例方法与除List[String]
之外的任何其他类型。另外请注意,在这种情况下,您不再需要输入[T]
作为方法 - 它来自封闭类。
也就是说功能参数设置:你的猜测是正确的:如果你传递的Ints
它List
,该函数将返回Int
,如果传递的Strings
List
,返回值应该是String
,等等。此外,您可以在功能范围内使用此类型,例如,像这样:
def foo[T](l: List[T]): T = {
...
val z = collections.mutable.HashMap[String,T]
...
}
T是“未绑定”类型。换句话说,List<T>
是“事物清单”的缩写。
这意味着您可以使用相同的代码,以使一个“日期列表”或“帐户列表”,“人名单”,你只需要提供构造
List<Person> people = new List<Person>();
将结合T
对人民。现在,当您访问List
时,它将保证前面没有绑定的任何地方都会存在,它就会像在该位置上写有“人员”一样。例如,public T remove(int)
将返回绑定到人员列表中的“人员”的T
。这避免了需要添加明确的强制转换。它还保证List
内的唯一项目是至少人。
List<Person> people = new List<Person>(); // T is bound to "People"
List<Account> accounts = new List<Account>(); // T is bound to "Account"
Person first = people.remove(0);
Account firstAccount = accounts.remove(0);
// The following line fails because Java doesn't automatically cast (amongst classes)
Account other = people.remove(0);
// as people is a List<T> where T is bound to "People", people.remove(0) will return
// a T which is bound to People. In short it will return something that is at least an
// instance of People. This doesn't cast into an account (even though there are other
// lists which would).
注意,至少人的评论是,该名单可能包含多个对象,但是所有的对象必须是人的子类的指标。
非常感谢。 – locrizak
Ahh ..所以如果你做'新的Foo [字符串]'所有'T's将是类型'字符串'? – locrizak
@locrizak。是。不仅编译器不会让你调用'new Foo [String] .firstElementInList(List(1,2,3)',而且'Foo [String]'和'Foo [Int]'被认为是完全不同的 –
非常感谢。非常有帮助 – locrizak