What's an elegant/right way in scala to string concatenate an Option so that None renders as an empty string and variables that have a value don't get wrapped in Some("xyz")
case class foo(bar: Option[String], bun: Option[String])
println(myFoo.bar+ "," + myFoo.bun)
The output I want is for example
hello,
instead of
Some(hello),None
when a new string is created by adding two strings is known as a concatenation of strings. Scala provides concat() method to concatenate two strings, this method returns a new string which is created using two strings. we can also use '+' operator to concatenate two strings.
The Option in Scala is referred to a carrier of single or no element for a stated type. When a method returns a value which can even be null then Option is utilized i.e, the method defined returns an instance of an Option, in place of returning a single object or a null.
In scala we can create string in two ways using string literal and b defining string. In this example we are creating a string object by assigning a String keyword before the literal. In this syntax we are using string literal to create a string object. Both the ways are same as java with some little modification.
One way would be:
val a = foo(Some("Hello"), None)
a.productIterator.collect{ case Some(s) => s }.mkString(",")
Another way would be:
Seq(bar, bun).flatten.mkString(",")
This doesn't do what you asked for, since it doesn't print the comma at the end, but I still suggested it since it might do what you want.
To get a value from Option
in a safe way use getOrElse
and provide a default argument, which would be used in case you Option
is None
. In your example it would look like this:
case class foo(bar: Option[String], bun: Option[String])
println(myFoo.bar.getOrElse("") + "," + myFoo.bun.getOrElse(""))
Then you'll get the required result
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With