In all the examples I am ready this kind of function definition keeps popping up:
def firstElementInList[T](l: List[T]): T
I’m used to seeing List[Int] so it would be a list of integers. In this case I’m assuming that T is any type (please correct me if im wrong). What I’m really getting caught up on is the [T] right after firstElementInList
IT is just a way to tell: this function references one generic type
T(you are rightTis any type).If you have multiple methods inside one class:
then each method has its own
Ttype, so you can call first method with a list ofStrings and a second one with a list ofInts.However the whole class enclosing both of these methods can have type as well:
In this case you pick type during
Fooobject creation:and the compiler will prevent you from calling instance methods of
foowith any other type thanList[String]. Also note that in this case you no longer need type[T]for a method – it is taken from the enclosing class.