更新List的最后一个元素 [英] update the last element of List

查看:190
本文介绍了更新List的最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表

val first = List("A","B","C","D")

,我想从中创建一个新列表,但只更改最后一个元素: p>

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

推荐答案

您也可以使用 .init .dropRight(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

这篇关于更新List的最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆