Scala for-loop. Getting index in consice way

后端 未结 4 1262
广开言路
广开言路 2020-12-31 16:17

In this code I want to increment index to put it to each yielding result.

var index=0

for(str <- splitToStrings(text) ) yield           


        
4条回答
  •  我在风中等你
    2020-12-31 16:46

    zipWithIndex will copy and create a new collection, so better make it lazy when the collection is potentially large

    for ((str, index) <- splitToStrings(text).view.zipWithIndex)
      yield new Word(str, UNKNOWN_FORM, index)
    

    In fact, if you are working with an indexed sequence, then a more efficient way is to use indices, which produces the range of all indices of this sequence.

    val strs = splitToStrings(text)
    
    for(i <- strs.indices) yield  {
      new Word(strs(i), UNKNOWN_FORM, i )
    }
    

提交回复
热议问题