I am trying to write a simple utility to check whether a JsValue
is null
or empty. I have this:
def is_nullOrEmpty(x: JsValue): JsBoolean = {
JsBoolean(
(x) match {
case _ => x == null
case _ => x.toString().isEmpty
}
)
}
I am fairly new to Scala + Play and I am not sure whether this is the correct way to go about.
Alternatively this:
def is_nullOrEmpty(x: JsValue) = x == null || x.toString().trim.isEmpty
Where I am also including .trim
Can you help?
You can use Option
. Please try the following:
def is_nullOrEmpty(x: JsValue): JsBoolean = Option(x) match {
case None =>
JsFalse
case Some(value) =>
if (Json.stringify(value) == "") {
JsFalse
} else {
JsTrue
}
}
Or even easier in one liner:
def is_nullOrEmpty1(x: JsValue): JsBoolean = JsBoolean(Option(x).exists(Json.stringify(_) != ""))
Having said that, the check of an empty string is redundant, as elaborated at Why does JSON.parse fail with the empty string? and in many other posts.
Code run at Scastie.