scala:用重载来修饰我的库
有什么想法为什么以下不起作用?
implicit def listExtensions[A](xs : List[A]) = new ListExtensions(xs)
class ListExtensions[A](xs : List[A])
{
def foreach[B](f: (A, Int) => B)
{
var i = 0;
for (el <- xs)
{
f(el, i);
i += 1;
}
}
}
var a = List(1, 2, 3);
a foreach { (el, i) => println(el, i) };
当我使用 fsc 2.8.1 编译此文件时,出现以下错误:“参数数量错误;预期 = 1: a foreach { (el, i) => println(el, i) };”。我是否做错了什么,或者根本没有办法通过“拉皮条我的库”技巧来添加重载方法?
PS 我不知道如何实现 foreach 的 iterate-with-current-index 风格(我知道 zipWithIndex 方法),而是想知道重载和隐式转换如何一起发挥作用。
Any ideas why doesn't the following work?
implicit def listExtensions[A](xs : List[A]) = new ListExtensions(xs)
class ListExtensions[A](xs : List[A])
{
def foreach[B](f: (A, Int) => B)
{
var i = 0;
for (el <- xs)
{
f(el, i);
i += 1;
}
}
}
var a = List(1, 2, 3);
a foreach { (el, i) => println(el, i) };
When I compile this with fsc 2.8.1, I get the following error: "wrong number of parameters; expected = 1: a foreach { (el, i) => println(el, i) };". Am I doing something wrong or there simply ain't a way to add an overloaded method by the means of "pimp my library" trick?
P.S. I wonder not about implementing the iterate-with-current-index flavor of foreach (I'm aware of zipWithIndex method), but rather about how overloading and implicit conversions play together.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
编译器永远不会尝试使用隐式转换,因为 List 上已经有一个 foreach 方法。更具体地说,Scala 语言规范 (http://www.scala-lang.org/docu/files/ScalaReference.pdf) 的第 7.3 节指出,隐式转换应用于两种情况,第二种情况与示例相关:
顺便说一句,您可以使用 zipWithIndex 方法完成带有索引的 foreach。
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:
As an aside, you can accomplish a foreach with an index by using the zipWithIndex method.
仅当您尝试使用源类型上不存在的方法时,隐式转换才会启动。
在这种情况下,List有一个foreach方法,因此不会考虑转换。但是您会因与预期签名不匹配而收到错误。
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.
或者,将名称更改为 foreachWithIndex
Or, change the name to foreachWithIndex