scala> Seq("abc", null).mkString(" ")
res0: String = abc null
but I want to get "abc" only
Is there a scala way to skip nulls?
scala> val seq = Seq("abc", null, "def")
seq: Seq[String] = List(abc, null, def)
scala> seq.flatMap(Option[String]).mkString(" ")
res0: String = abc def
flatMap approach. This is what I would expect out of idiomatic Scala. It's also good to know that Option(null) reliably returns "None"There's always Seq("abc", null).filter(_ != null).mkString(" ")
Seq("abc", null).iterator.filter(_ != null).mkString(" ") to avoid building the intermediate collection.withFilter for that, don't they? Update: Just tried it - apparently mkString doesn't work directly with withFilterCombination of Rex's answer and Eric's first comment:
Seq("abc", null).map(Option(_)).collect{case Some(x) => x}.mkString(" ")
The first map wraps the values resulting in Seq[Option[String]]. collect then essentially does a filter and map, discarding the None values and leaving only the unwrapped Some values.
Seq("abc", null).flatMap(Option(_)).mkString(" "). Flatten does what you want it to.
Option[String]as your type, andNoneinstead ofnull.flatMap(s=>s)can be written more succinctly asflatten.