1

I want to iterate over a list of strings, concatenate them with the suffix/prefix "" and if it's not the last entry of the list append a comma at end.

Wanted Output example: "circle","cube","banana"

My first try is the following snippet:

@listStringifier(list: List[String]) = @{
  if (list != null && !list.isEmpty) {
   for ((string, index) <- list.zipWithIndex){if(index != list.size-1){"string",}
   else{"string"}
   }
  }
}

But this function is always empty when I use @listStringifier anywhere.

Logging within the @listStringifier block shows that it is iterating, but not assigning anything.

If I call the for loop directly in the template like this following snippet it works:

@if (list != null && !list.isEmpty) {
  for ((string, index) <- list.zipWithIndex){if(index != list.size-1){"@string",}
  else{"@string"}
  }
}

But I dont want to iterate several times so I want to assign the concatenated string to a variable afterwards.

Any help would be appreciated, thanks in advance

Yeti
  • 63
  • 7

2 Answers2

3

I think mkString can do what you want

list.mkString( "'" , "','" , "'" )
Thilo
  • 257,207
  • 101
  • 511
  • 656
  • Thanks for mentioning, that was exactly what I'm looking for so I replaced the single quotation mark with the double quotation marks and it worked like a charm. Like this: `list.mkString( "\"" , "\",\"" , "\"" )` Thank you for your help – Yeti Sep 14 '16 at 08:36
  • Yeah, I put single quotes to not go crazy on the escape sequences (is there a way in Scala to have alternative String delimiters like Perl's `q{","}`?) – Thilo Sep 14 '16 at 08:37
  • I don't know mate, sorry – Yeti Sep 14 '16 at 08:43
1

mkString can do this elegantly

@listStringifier(list: List[String]) = @{ list mkString("", ",", "") }

if you want quotes around the strings you could do

list.map(str => s""""$str"""").mkString(",")
Nagarjuna Pamu
  • 14,737
  • 3
  • 22
  • 40
  • `(""""""", """" ,"""", """"""")` was requested. – som-snytt Sep 14 '16 at 08:08
  • thanks for mentioning, I tried this before, but that would only append the quotes to the very first and last sign unfortunately. – Yeti Sep 14 '16 at 08:13
  • @Yeti: You can add the quotes to the separating comma as well to work around that. – Thilo Sep 14 '16 at 08:25
  • @Thilo as mentioned in your answer it works now, thank you all for your help. I cannot mark both answers as correct, indeed they are from the point of syntax – Yeti Sep 14 '16 at 08:37