Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the point of generic type in foreach?

Tags:

I'm curious - what is the point of generic type U in declaration of Traversable's foreach method?

def foreach[U](f: A => U): Unit

Since return type of Function1 is covariant, why can't that be just:

def foreach(f: A => Any): Unit

?

like image 968
ghik Avatar asked Dec 30 '12 20:12

ghik


People also ask

Why use generics instead of Object?

Generics could be used to develop a better solution using a container that can have a type assigned at instantiation, otherwise referred to as a generic type, allowing the creation of an object that can be used to store objects of the assigned type.

Why are generics useful?

In a nutshell, generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs.

Why parameterized type is important in Java?

Like generics in C# and Java, parameterized types allow you to create “containers” that can hold other types. For example, List<String> represents a List containing only strings, and KeyValuePair<int, string> represents a pair of values in which an int serves as a key to a string .


1 Answers

Not being Martin Odersky, I can only guess :-) Looking at the Scaladoc of foreach, I see this:

  /** Applies a function `f` to all elements of this $coll.
   *
   *  @param  f   the function that is applied for its side-effect to every element.
   *              The result of function `f` is discarded.
   *              
   *  @tparam  U  the type parameter describing the result of function `f`. 
   *              This result will always be ignored. Typically `U` is `Unit`,
   *              but this is not necessary.
   *
   *  @usecase def foreach(f: A => Unit): Unit
   */

So the return type of f doesn't matter and its result is always discarded. This, to me, suggests that using a generic type parameter here to mark the return type is just a documentation subtlety, saying "the return type can be anything, really anything, you like". Whereas a return type of Any may suggest to (some) readers some sort of limitation to the function types applicable here.

Another aspect is that Scala was very consciously designed to be generic from the ground up. So - to me - using a generic type parameter here is consistent with the general philosophy of the language, while using Any - although technically usable - would be a definitely non-generic approach which would be at odds with the rest of the language.

like image 183
Péter Török Avatar answered Sep 21 '22 00:09

Péter Török