Scala Language Parameterized Methods


The return type of a method can depend on the type of the parameter. In this example, x is the parameter, A is the type of x, which is known as the type parameter.

def f[A](x: A): A = x

f(1)         // 1
f("two")     // "two"
f[Float](3)  // 3.0F

Scala will use type inference to determine the return type, which constrains what methods may be called on the parameter. Thus, care must be taken: the following is a compile-time error because * is not defined for every type A:

def g[A](x: A): A = 2 * x  // Won't compile