How to combine option in scala

What elegant / correct way in scala for a string combines a parameter, so that None displays as an empty string, and variables that matter are not wrapped in Some ("xyz")

case class foo(bar: Option[String], bun: Option[String]) println(myFoo.bar+ "," + myFoo.bun) 

The output I want, for example, is

 hello, 

instead

Some(hello),None

+5
source share
3 answers

To safely use the Option value, use getOrElse and specify the default argument, which will be used if you are Option None . In your example, it will look like this:

 case class foo(bar: Option[String], bun: Option[String]) println(myFoo.bar.getOrElse("") + "," + myFoo.bun.getOrElse("")) 

Then you get the desired result.

+6
source

One of the methods:

 val a = foo(Some("Hello"), None) a.productIterator.collect{ case Some(s) => s }.mkString(",") 

Another way:

 Seq(bar, bun).flatten.mkString(",") 

This does not do what you asked for, because in the end it does not print a comma, but I still suggested it, because it can do what you want.

+9
source

First: to turn a Option[String] into a String :

 opt.getOrElse("") 

or if you prefer a more syntactic call to the operator call:

 opt getOrElse "" 

then getOrElse can be shortened with an alias | provided by Scalaz :

 import scalaz._, Scalaz._ opt | "" 

Alternatively, you can let Scalaz figure out what the "" for you; this works thanks to having a Monoid instance defined for String that defines the empty (or null) String value for the empty string:

 opt.orZero 

Total:

 scala> ("hello".some).orZero + " blabla " + ("world".some).orZero res9: String = hello blabla world scala> (none[String]).orZero + " blabla " + ("world".some).orZero res10: String = " blabla world" scala> ("hello".some).orZero + " blabla " + (none[String]).orZero res11: String = "hello blabla " 

(here I use Scalaz none and some , with Scala vanilla you need to write None: Option[String] and Some("hello"): Option[String to get the types you need)


However ... you probably want to avoid this extraneous space, so in practice you would use something in the lines; above all for training / research:

 scala> List("hello".some, Some("blabla"), "world".some).flatten.mkString(" ") res0: String = hello blabla world scala> List("hello".some, none[String], "world".some).flatten.mkString(" ") res1: String = hello world 

- note that between words there is always only one space between words.

+2
source

Source: https://habr.com/ru/post/1208470/


All Articles