问题
I have a List
val first = List("A","B","C","D")
and I want to create a new list from it but change the last element only:
val newLastVal = "E"
val second = List("A","B","C","E")
can't figure this one out! Thanks in advance
回答1:
you can also use .init
or .dropRight(1)
to remove last element and then can add new item to list
val second=first.init:+newLastVal //preferable
OR
val second=first.dropRight(1):+newLastVal
回答2:
you can use .updated(postion,value)
val second=first.updated(first.length-1,newLastVal)
来源:https://stackoverflow.com/questions/24838826/update-the-last-element-of-list