How can I use map and receive an index as well in Scala?

前端 未结 8 1836
轮回少年
轮回少年 2020-12-12 23:07

Is there any List/Sequence built-in that behaves like map and provides the element\'s index as well?

8条回答
  •  孤街浪徒
    2020-12-12 23:50

    There is CountedIterator in 2.7.x (which you can get from a normal iterator with .counted). I believe it's been deprecated (or simply removed) in 2.8, but it's easy enough to roll your own. You do need to be able to name the iterator:

    val ci = List("These","are","words").elements.counted
    scala> ci map (i => i+"=#"+ci.count) toList
    res0: List[java.lang.String] = List(These=#0,are=#1,words=#2)
    

提交回复
热议问题