lak
lak

Reputation: 143

How can I prepend a string to list of elements in Scala?

I have the following requirement:

val lst = List("a","b","c")

I would like to prepend with the text test to all the elements in the list. The output should be like as below:

testa
testb
testc

Upvotes: 3

Views: 815

Answers (4)

tmucha
tmucha

Reputation: 709

If you want to create list with such elements you could write: val result = list.map("test" + _)

After that of course you could print them all: result foreach println

Upvotes: 1

SCouto
SCouto

Reputation: 7926

Just to add some more options:

If you want a new List with the elements as you said:

val newList = lst.map("test".concat(_))

If you just want to print them, then you can do something like this:

lst.foreach(item => println(s"test$item"))

Upvotes: 1

gil.fernandes
gil.fernandes

Reputation: 14641

In order to get that output you can write:

def main(args: Array[String]): Unit = {
  val lst = List("a","b","c")
  lst.map(s => "test" + s).foreach(println)
}

Upvotes: 0

JCollerton
JCollerton

Reputation: 3327

val alteredList = lst.map(item => "test" + item)

Upvotes: 3

Related Questions