简体   繁体   中英

Handle java.lang.NullPointerException in scala when accessing nested fields

I have a use case where

    name = Person.getFirstSister().getname()

Person.getSister().getname() gives java.lang.NullPointerException since Person.getSister() is java null

What is the right way to do this in scala. I am able to achieve with below code. But looking for more scala way of doing it.

  private def getFirstSisterName(person: Person): String = {
    val sister = person.getFirstSister()
    if (sister == null) ""
    else sister.getName()
  }

Checking for null is the Java way to go. Scala offers a much more streamlined set of operations to avoid doing null checks manually.

The natural way would be to have getSister result in an Option[Sister] , the argument being that not every person has a sister.

Going on the same idea, trying to mimic the real word, I would ask: but what if a person has multiple sisters? How do you distinguish between them? This implies your design is not very general because it implies every person has a sister.

The natural way is to have a getSisters return a List[Sisters] . Then map their names from the list. If the list is empty, no problem, Nil represents an empty list, so we won't have any null problems:

  case class Sister(name: String)

  case class Person(sisters: List[Sister]) {
    def sistersNames: String = sisters.map(_.name).mkString(" ")
  }

  val p = Person(List(Sister("Sandra"), Sister("Joanna")))
  val p2 = Person(List.empty)

  println(p.sistersNames)    // Sandra Joanna
  println(p2.sistersNames)   // empty String

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM