[英]scala case class initialisation
Below is my case classes. 下面是我的案例类。 How to initialise case class child in scala? 如何在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. 如果我声明为null,则在其他情况下将抛出NullPointerException
。 How to solve that? 怎么解决呢?
I don't think you should unwrap the Option[Child]
so that it would be null
if it was empty. 我不认为您应该拆开Option[Child]
以便如果为null
则将其为null
。 You shouldn't use nulls when you write idiomatic Scala. 编写惯用的Scala时,不应使用null。 I would keep it in an Option
and use the map
and flatMap
methods on it, to access the child if it exists. 我将其保留在Option
并在其上使用map
和flatMap
方法访问该子项(如果存在)。
However, if you really want to, you can do it like this: 但是,如果您确实想这样做,可以这样做:
val a: Child = x.child.getOrElse(null)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.