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

前端 未结 8 1823
轮回少年
轮回少年 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-13 00:02

    Use .map in .zipWithIndex

    val myList = List("a", "b", "c")
    
    myList.zipWithIndex.map { case (element, index) => 
       println(element, index) 
       s"${element}(${index})"
    }
    

    Result:

    List("a(0)", "b(1)", "c(2)")
    

提交回复
热议问题