Reputation: 53916
In the method signature for groupBy :
def groupBy[K](f : (A) => K) : Map[K, This]
How is the type parameter of [K] on groupBy typed ? What is the significance of [k] in this context : groupBy[K] . Why is the type parameter required here, is this a requirement of Scala that cannot use instead : def groupBy(f : (A) => K) : Map[K, This]
?
Upvotes: 0
Views: 111
Reputation: 31873
K is specified first because the type of the KeySelector function, (A) => K, and the type of the result :Map[K, this] depend on its definition. K is the type parameter that allows the groupBy implementation to abstract over grouping by a Key of any type.
Upvotes: 0
Reputation: 297265
How is the type parameter of [K] on groupBy typed ?
From the type of the function passed to groupBy
, unless passed explicitly.
What is the significance of [k] in this context : groupBy[K] .
It is a type parameter: a type that is not fixed at the definition site of groupBy
, but, instead, varies and depends on the context at each usage site of this method.
Why is the type parameter required here, is this a requirement of Scala that cannot use instead : `def groupBy(f : (A) => K) : Map[K, This]` ?
It is a requirement. In the definition you provide, the function passed to groupBy
must be from A
(a type parameter of the class) to K
, a fixed type known at the definition of groupBy
. Since there's no type K
in Scala, that would automatically an error.
Or, to put in another way, it would be like defining groupBy
as def groupBy(f: (A) => String): Map[String, This]
.
Upvotes: 2
Reputation: 4161
The List is defined in the scaladoc as sealed abstract class List[+A]
- so A is the type of elements in the list. You can group the list's elements by any function f: (A) ⇒ K
, which is to say that K can be any type. If you are going to notify the compiler that you can group by "a function f: (A) ⇒ K
, where K is some type", you need to declare the symbol K. This is done at the method level, because K is only used at the method level. This is accomplished by declaring def groupBy[K](f: (A) ⇒ K): Map[K, List[A]]
. Hope this is clear.
Upvotes: 0
Reputation: 1727
K is a method level type parameter, it does not exist for the class. so what you propose would not make sense. K needs to be declared as a type parameter also, because im assuming you do not want to reference type K, but rather the type variable K.
Upvotes: 1