Scala List of String Option[String] using with mkString

时间:2015-06-30 13:43:03

标签: scala

I have a List which can have a String or Option[String]

like this

val a = List("duck","dog","cat")

a.mkString(:)

duck:dog:cat

val b = List(Some("duck"), "dog", None)

and my output should be

"duck:dog"

How can I do that, I get some aproximation with this:

scala> a.map{ x =>
     | x match {
     | case x:String => x
     | case Some(x:String) => x
     | case None => null}}

List[String] = List(duck, dog, null)

scala> res.filter(_!=null).mkString(":")
res24: String = duck:dog

Is there a better way, of doing that?

3 个答案:

答案 0 :(得分:4)

这是使用collect的完美示例。 我们想创建一个只包含部分元素的列表,然后我们想使用mkString

val b = List(Some("duck"), "dog", None)

val result: List[String] = b collect {
  case x: String => x
  case Some(x: String) => x
}
result.mkString(":")

答案 1 :(得分:1)

You could flatMap to get rid of the filter:

  b.flatMap {
    case x: String => List(x)
    case Some(x) => List(x)
    case None => List()
  }.mkString(":")

or you could filter before the map:

  b.filter(_ != None).map {
    case x: String => x
    case Some(x) => x
  }.mkString(":")

答案 2 :(得分:0)

这是null

的安全之处
scala> val l = List(Some("duck"), "dog", None, null)
l: List[java.io.Serializable] = List(Some(duck), dog, None, null)

scala> l.map{a => a match { 
       | case null => "" 
       | case Some(a) => Some(a).get.toString 
       | case None => "" 
       | case _ => a.toString}}.filter(_.length > 0).mkString(":")

res7: String = duck:dog
相关问题