Idiomatic way of converting multiple Options into list

  • A+
Category:Languages

I quite often encounter a problem of converting mostly optional settings-like object into strings or lists (e.g. into arguments for launching some external program). Usually I end up with imperative code similar to this:

case class Options(host: Option[String], user: Option[String], password: Option[String]) {   def argsString = {     val args = new ArrayBuffer[String]()      if (host.nonEmpty) {       args+="--host"       args+=host.get     }      if (user.nonEmpty) {       args+="--user"       args+=user.get     }      if(password.nonEmpty) {       args+="--password"       args+=password.get     }      args mkString " "   } } 

Is there a more FP-like way of doing this?

 


There are a few ways. This should work:

case class Options(host: Option[String], user: Option[String], password: Option[String]) {   def argsString: String = {      host.map("--host " + _) ++      user.map("--user " + _) ++      password.map("--password " + _)    }.mkString(" ") } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: