简体   繁体   中英

update the last element of List

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

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

你可以使用.updated(postion,value)

val second=first.updated(first.length-1,newLastVal)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM