Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple type parameters on a scala method

In Java, a Map could be parameterized as Map<K, V>, but in Scala, I don't know what's the meaning of multiple type parameters on a method, for example:

def foo[T, U, R]

It is easy to understand when a method parameterized by one type parameter. such as def f[T](t: T) .

like image 851
user2018791 Avatar asked Jul 11 '14 14:07

user2018791


1 Answers

Suppose I want to write a generic method that operates on any old Map[K, V]—I'd have to include both type parameters in the method type parameter list:

def mapToList[K, V](m: Map[K, V]): List[(K, V)] = m.toList

Three parameters works the same way. Suppose I have a function A => B and another B => C, and I want to compose them to get a function from A to C—I need all three types in my parameter list:

def andThen[A, B, C](f: A => B, g: B => C): A => C = (a: A) => g(f(a))

Both of these examples are trivial, since we already have m.toList and f andThen g, but they should make the use case for multiple type parameters clear.

like image 55
Travis Brown Avatar answered Nov 01 '22 00:11

Travis Brown