Scala: Traversable foreach definition

☆樱花仙子☆ 提交于 2021-01-08 06:29:33

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!