Skip to content

Instantly share code, notes, and snippets.

@hanbzu
Last active December 26, 2015 18:39
Show Gist options
  • Save hanbzu/7196172 to your computer and use it in GitHub Desktop.
Save hanbzu/7196172 to your computer and use it in GitHub Desktop.
Scala: Concatenate Lists of Strings with mkString
// A list of strings into a single string
val food = "rice" :: "cookies" :: "watermelon" :: Nil
food.foldLeft("")(_ + ", " + _)
// But we would have to remove the first two chars:
// ", rice, cookies, watermelon"
// Now with mkString
val fruits = "apple" :: "orange" :: "kiwi" :: Nil
fruits mkString ", "
// If each element could be an option we need to flatten
val animals = None :: Some("monkey") :: Some("koala") :: Nil
animals.flatten mkstring ", "
// It's possible to filter for empty lists
val clothes = "trousers" :: "hat" :: "" :: "shirt" :: Nil
clothes filter {_.nonEmpty} mkString ", "
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment