Scala:用超载拉皮条我的库 [英] scala: pimp my library with overloads

查看:69
本文介绍了Scala:用超载拉皮条我的库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何想法为何以下工作无效?

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) };

当我使用fsc 2.8.1进行编译时,出现以下错误:参数数量错误;期望= 1:foreach {(el,i)=> println(el,i)};".我是在做错什么,还是根本没有办法通过"pimp my library"的技巧来添加重载的方法?

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.我想知道不是要实现foreach的迭代与当前索引的风格(我知道zipWithIndex方法),而是想知道重载和隐式转换如何一起起作用.

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.

推荐答案

编译器从不尝试使用隐式转换,因为List上已经有一个foreach方法.更具体地说,Scala语言规范(http://www.scala-lang.org/docu/files/ScalaReference.pdf)的7.3节指出,在两种情况下都应用了隐式转换,第二种情况与示例相关:

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:

在选择类型为e的选择e.m中,如果选择器m不表示T的成员.

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

顺便说一句,您可以使用zipWithIndex方法用索引完成foreach.

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

这篇关于Scala:用超载拉皮条我的库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆