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
.
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 ).
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.
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.
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.
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 }
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
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