Scala case pattern matching error in case of [String] option

I am trying to create a function with a variable number of arguments

def foo(args: String*)

      

What this function does is it eliminates blank lines and individual semicolon ( ,

) lines .

def foo(args: String*) = {
  args.flatMap {
    case str if str.isEmpty => None
    case str => Some(str)
  }.mkString(", ")
}

      

When I extended this function to support arguments Option[String]

def foo(args: Any*) = {
  args.flatMap {
    case str: String if str.isEmpty => None
    case str: Option[String] if str.getOrElse("").isEmpty => None
    case str => Some(str)
  }.mkString(", ")
}

      

I got a warning that

warning: type argument without variable String in type template [String] parameter not set because it is cleared by erasure

And when I pass the arguments

foo("", "Hello", Some(""), Some("what"))

      

I got error

scala.MatchError: Some (what) (scala.Some class) in $ anonfun $ makeAddress $ 1.apply (: 12) at $ Anonfun $ makeAddress $ 1.Apply (: 12)

How do I create such a feature that supports Option[String]

?

+3


source to share


2 answers


You can use a collection and exclude the option entirely:

def foo(args: String*): String = {
  args.collect{case s if ! s.isEmpty => s}.mkString(",")
}

      



collect is the equivalent of a filter combined with a map.

+3


source


Like your solution



def foo(args: Any*) = {
  args.flatMap {
    case str: String if !str.isEmpty => Option(str)
    case Some(str:String) if !str.isEmpty  => Option(str)
    case _ => None
  }.mkString(", ")
}

      

+1


source







All Articles