update the last element of List

吃可爱长大的小学妹 提交于 2019-12-10 09:23:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!