Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting with an Option[String] in Scala

Tags:

scala

I'm trying to find a concise way to format a String with an Option[String] in Scala. I have a title String and a subtitle Option[String]. Here's what I have but I feel like there has to be a better way:

"Title%s".format(subtitle match
    {case Some(s) => ": %s".format(s)
     case None    => "" })

So if I have a subtitle, I want "Title: Subtitle", but if subtitle is None, I just want "Title".

like image 475
mplis Avatar asked Oct 04 '13 13:10

mplis


People also ask

How can you format a string in Scala?

In Scala Formatting of strings can be done utilizing two methods namely format() method and formatted() method. These methods have been approached from the Trait named StringLike.

What is option string 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.

What does string * mean in Scala?

In Scala, as in Java, a string is an immutable object, that is, an object that cannot be modified. On the other hand, objects that can be modified, like arrays, are called mutable objects. Strings are very useful objects, in the rest of this section, we present important methods of java. lang.

How do you use some and options in Scala?

An Option[T] can be either Some[T] or None object, which represents a missing value. For instance, the get method of Scala's Map produces Some(value) if a value corresponding to a given key has been found, or None if the given key is not defined in the Map.


1 Answers

 subtitle map (t => s"Title: $t") getOrElse ("Title") 

String interpolation is more safe than format because if you don't use correct variable name, or missuse it somehow it will fail at compile time. format will fail at run time if the number of placeholders or their types do not match format arguments.

Your version of Scala must support this feature and have it enabled.

like image 83
yǝsʞǝla Avatar answered Sep 28 '22 02:09

yǝsʞǝla