简体   繁体   中英

scala case class initialisation

Below is my case classes. How to initialise case class child in scala?

// case class 
case class parent(id: String, name: String, rNo: Int,
                  child: Option[Child])

case class Child(cid: String, Ctype: String,
                 group_category_id: String,
                 unlock_at: String, due_at: String)

val a: Child = if (x.child != None) { x.child.get } else { null }

If I declare as null, it will throw NullPointerException in case of else condition. How to solve that?

I don't think you should unwrap the Option[Child] so that it would be null if it was empty. You shouldn't use nulls when you write idiomatic Scala. I would keep it in an Option and use the map and flatMap methods on it, to access the child if it exists.

However, if you really want to, you can do it like this:

val a: Child = x.child.getOrElse(null)

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