Overloading the map method in list

Would it be a good idea to have a overloaded map method that accepts a function of type

def map[B](f: (e: A, i: Int) => B)

Basically the i is the index of the element that is under process. I know we can use zipWithIndex but I really can’t afford to iterate the list twice. Will list.view.zipWithIndex have a better performance?

What’s your though on the above overloaded method?

1 Like

Overloading is rarely a good idea. That being said, we’re doing it extensively in the new collections library. Adding an extra map overload would break this scheme (at least if you were to add it at the Iterable level where it makes sense). The method should really be called mapWithIndex.

The two extra Views in .view.zipWithIndex shouldn’t make a big difference (relative to the high overhead and bad locality of List), but I expect the extra tuple per element will. You should really do some benchmarking if you want to make a case for adding mapWithIndex.

Note that both versions need to box the Int argument. Both Tuple2 and Function2 are specialized for Int but neither one is specialized for AnyRef, so with the other type being A <: Any there is no way to use a specialized implementation.

Didn’t quite get the last paragraph!

With a definition like def map[B](f: (e: A, i: Int) => B) you may expect that the Int can be an unboxed primitive because you can have a method type [A](e: A, i: Int): B with an unboxed Int. I was merely pointing out that, perhaps non-intuitively, the specialized Function2 can not do this.

The only advantage compared to the tupled definition is that you do not need to wrap the arguments in a Tuple2. And since Tuple2 is specialized in the same way as Function2 it suffers from the same restrictions, so the tupled version still needs the Integer wrapper in addition to the Tuple2.