This is just a way of saying: this function refers to one common type T
(you are right T
is any type).
If you have multiple methods inside the same class:
def firstElementInList[T](l: List[T]): T = l.head def lastElementInList[T](l: List[T]): T = l.last
then each method has its own type T
, so you can call the first method with the String
list, and the second with the Int
s list.
However, an entire class containing both of these methods can be of type:
class Foo[T] { def firstElementInList(l: List[T]): T = l.head def lastElementInList(l: List[T]): T = l.last }
In this case, you select the type when creating the Foo
object:
val foo = new Foo[String]
and the compiler will not allow you to call Foo
instance methods with any type other than List[String]
. Also note that in this case you no longer need the type [T]
for the method - it is taken from the surrounding class.
source share