scala: pimp my library with overloads

放肆的年华 提交于 2019-12-06 11:44:23

The compiler never attempts to use the implicit conversion because there's already a foreach method on List. More specifically, section 7.3 of the Scala Language Specification (http://www.scala-lang.org/docu/files/ScalaReference.pdf) states that an implicit conversion is applied in two cases, with the second case relevant to the example:

In a selection e.m with e of type T, if the selector m does not denote a member of T.

As an aside, you can accomplish a foreach with an index by using the zipWithIndex method.

scala> val a = List("Java", "Scala", "Groovy")
a: List[java.lang.String] = List(Java, Scala, Groovy)

scala> a.zipWithIndex.foreach { case (el, idx) => println(el + " at index " + idx) } 
Java at index 0
Scala at index 1
Groovy at index 2

Implicit conversion will only kick in when you attempt to use a method that doesn't exist on the source type.

In this case, List has a foreach method, so no conversion will be considered. But you will get an error for not matching the expected signature.

(a : ListExtensions[Int]) foreach { (el, i) => println(el, i) };

Or, change the name to foreachWithIndex

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