You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Scala中为列表所有元素前置指定字符串?

解决Scala列表元素添加前缀并拼接的问题

Hey there! I've got you covered on this Scala task. Let's walk through how to add the prefix "test" to each element in your list and output them as a space-separated string.

最直接的实现方式

The core idea is to first transform each element in the list with the prefix, then join them together with spaces. Here's the straightforward code:

val lst = List("a","b","c")
// 先给每个元素添加前缀,再用空格拼接
val prefixedAndJoined = lst.map(element => "test" + element).mkString(" ")
println(prefixedAndJoined) // 输出: testa testb testc

更简洁的写法

Scala lets us write this more concisely if you prefer:

  • Using string interpolation:
    val prefixedAndJoined = lst.map(element => s"test$element").mkString(" ")
    
  • Using the underscore shortcut for single-parameter functions:
    val prefixedAndJoined = lst.map("test" + _).mkString(" ")
    

All these approaches do exactly the same thing: they iterate over each element, prepend "test" to it, then combine the resulting list into a single string with spaces between elements.

If you want to print the result directly without storing it in a variable, you can even do it in one line:

println(lst.map("test" + _).mkString(" "))

内容的提问来源于stack exchange,提问作者lak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:55:02