问题
I suppose foreach
method in Traversable
trait is defined as follows:
def foreach[U](f: Elem => U)
Should it be defined as foreach[U,Elem](f:Elem =>U)
as there are two types, Elem
and U
?
回答1:
foreach[U](A => U)
is a method in the trait Traversable[+A]
.
trait Traversable[+A] extends TraversableLike[A, ...] {
...
}
trait TraversableLike[+A, ...] extends ... {
...
def foreach[U](f: A => U): Unit
...
}
https://github.com/scala/scala/blob/2.12.x/src/library/scala/collection/TraversableLike.scala#L124
回答2:
The Elem
type comes from the generic type of the Traversable
. The input to the function must the the same type as the elements of the Traversable
so it doesn't make sense to redefine it at the method call site.
来源:https://stackoverflow.com/questions/46835288/scala-traversable-foreach-definition