Last active
December 26, 2015 18:39
-
-
Save hanbzu/7196172 to your computer and use it in GitHub Desktop.
Scala: Concatenate Lists of Strings with mkString
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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