Why List and not List[Int]? What does T mean?

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 right T is any type).

If you have multiple methods inside one 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 T type, so you can call first method with a list of Strings and a second one with a list of Ints.

However the whole class enclosing both of these methods can have type as well:

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

In this case you pick type during Foo object creation:

val foo = new Foo[String]

and the compiler will prevent you from calling instance methods of foo with any other type than List[String]. Also note that in this case you no longer need type [T] for a method - it is taken from the enclosing class.

Need Your Help

Invoking dynamic Method without known Constructor?

java reflection dynamic

If I do this in Java to call a method name from a class dynamically, it works.

Bootstrap tabs transparent underline

html css twitter-bootstrap tabs

I'm trying to make the underline from the active / hovered tab transparent. But I didn't get it working. Anyone knows how to do this?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.