Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting empty string to a None in Scala

Tags:

scala

I have a requirement to concatenate two potentially empty address lines into one (with a space in between the two lines), but I need it to return a None if both address lines are None (this field is going into an Option[String] variable). The following command gets me what I want in terms of the concatenation:

Seq(myobj.address1, myobj.address2).flatten.mkString(" ")

But that gives me an empty string instead of a None in case address1 and address2 are both None.

like image 415
gmazza Avatar asked Feb 04 '15 21:02

gmazza


People also ask

Can we convert empty string to number?

Multiplying a string by 1 ( [string] * 1 ) works just like the unary plus operator above, it converts the string to an integer or floating point number, or returns NaN (Not a Number) if the input value doesn't represent a number. Like the Number() function, it returns zero ( 0 ) for an empty string ( '' * 1 ).

Is not empty in Scala?

Scala Iterator nonEmpty() method with exampleThe nonEmpty method belongs to the concrete value member of the class Abstract Iterator. It is utilized to check whether the stated collection is not empty. Return Type: It returns true if the stated collection contains at least one element else returns false.

Is null in Scala?

Null is - together with scala. Nothing - at the bottom of the Scala type hierarchy. Null is the type of the null literal. It is a subtype of every type except those of value classes.

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.


2 Answers

This converts a single string to Option, converting it to None if it's either null or an empty-trimmed string:

(kudos to @Miroslav Machura for this simpler version)

Option(x).filter(_.trim.nonEmpty)

Alternative version, using collect:

Option(x).collect { case x if x.trim.nonEmpty => x }
like image 55
juanmirocks Avatar answered Sep 23 '22 15:09

juanmirocks


Assuming:

val list1 = List(Some("aaaa"), Some("bbbb"))
val list2 = List(None, None)

Using plain Scala:

scala> Option(list1).map(_.flatten).filter(_.nonEmpty).map(_.mkString(" "))
res38: Option[String] = Some(aaaa bbbb)

scala> Option(list2).map(_.flatten).filter(_.nonEmpty).map(_.mkString(" "))
res39: Option[String] = None

Or using scalaz:

import scalaz._; import Scalaz._
scala> list1.flatten.toNel.map(_.toList.mkString(" "))
res35: Option[String] = Some(aaaa bbbb)

scala> list2.flatten.toNel.map(_.toList.mkString(" "))
res36: Option[String] = None
like image 30
dk14 Avatar answered Sep 23 '22 15:09

dk14