Search json key and return empty list if its value is an empty string

Viewed 73

This code doesn't handle empty string values well:

val getPerson = (json \ "ID").asOpt[String].map(id => List(Person(name, id, birthday))).getOrElse(List.empty)

Problem is that ID can be an empty string, Person's constructor allows id to be empty (by design) but I don't want Persons with no ID at this stage.

I tried:

val getPerson = (json \ "ID").asOpt[String].map(id => if (id.nonEmpty) List(Person(name, id, birthday))).getOrElse(List.empty)

but then the return type is Any instead of List[Person]

My goal is in cases of an empty id return List.empty

2 Answers

In addition to @pme answer, the reason that you should use List.empty[Type] (Whether String or Person) and not List.empty is because List.empty is actually of type List[Nothing].

Because you returned List[Person] in one case and List[Nothing] in the other, you had a return type of Any.

Anyway, when you are dealing with empty collections (Seq, List,..), you should always prefer List/Seq.empty[Type], because it's a clearer expression of your intent and it doesn't require the instantiation of an (empty) repeated-params argument list.

Just add the type to List.empty, e.g:

scala> List.empty[String]
res0: List[String] = List()

In your example filter may be a nicer solution:

val person = (json \ "ID")
                   .asOpt[String]
                   .filter(_.nonEmpty)
                   .toList
                   .map(Person(name, _, birthday))
Related