Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to concatenate option in scala

Tags:

scala

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

like image 480
MonkeyBonkey Avatar asked Dec 05 '14 23:12

MonkeyBonkey


People also ask

How do I concatenate in scala?

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.

How do I use options in scala?

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.

How do you create a string in scala?

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.


2 Answers

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.

like image 94
My other car is a cadr Avatar answered Sep 24 '22 13:09

My other car is a cadr


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

like image 36
4lex1v Avatar answered Sep 24 '22 13:09

4lex1v