Scala: Fill the gaps in a List with last non-empty value

前端 未结 3 966
灰色年华
灰色年华 2021-01-24 18:37

I have a list like:

val arr = Array(\"a\", \"\", \"\", \"b\", \"c\", \"\")

I am looking for a way to create:

Array(\"a\", \"a\"         


        
3条回答
  •  不要未来只要你来
    2021-01-24 19:28

    I think Mohitt's answer is a clear solution ... but Pablo Francisco Pérez Hidalgo is right that there are side effects

    Maybe we could include the variable inside of a function to avoid changing the temp variable by some other developers

    (x: Array[String]) => { var last = ""; x.map { v => if (v != "") last = v; last } }
    

    to be used like this:

    val fillEmpty = (x: Array[String]) => { var last = ""; x.map { v => if (v != "") last = v; last } }
    fillEmpty(arr)
    

提交回复
热议问题