如何在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

