简体   繁体   English

在Scala中处理java.lang.NullPointerException

[英]Handle java.lang.NullPointerException in Scala

Say I have a model class as shown below: 假设我有一个模型类,如下所示:

class User () {
  var id: Option[java.lang.Long] = _
  var name: Option[String] = _
  var date: Option[java.util.Date] = _

  def this(id: java.lang.Long,name: String, date: java.util.Date){
    this()
    this.id=Option(id)
    this.name=Option(name)
    this.date=Option(date)
  }
}

I tried to create an object by doing 我试图通过这样做来创建一个对象

var obj = new User
obj.id=12345
obj.name=user

Obviously obj.date is null , and I kept getting a java.lang.NullPointerException at this point. 显然obj.datenull ,此时我一直收到java.lang.NullPointerException How should I handle this exception? 我该如何处理这个例外?

I would advise you to initialize the values directly through the constructor. 我建议你直接通过构造函数初始化值。 This looks like a POSO (Plain Old Scala Object), so maybe you would be better off with an immutable case class: 这看起来像一个POSO(普通的旧Scala对象),所以也许你会更好用一个不可变的case类:

case class User(id: Option[Long], name: Option[String], date: Option[Date])

Now if you want to initialize only some of the properties, you can either pass None or create an auxiliary constructor via the companion object: 现在,如果只想初始化某些属性,可以通过伴随对象传递None或创建辅助构造函数:

case class User(id: Option[Long], name: Option[String], date: Option[Date])
object User {
  def apply(id: Option[Long], name: Option[String]) = {
    User(id, name, None)
  }
}

Edit: 编辑:

If Java interop is important, you can define multiple constructors inside the case class which will be visible in Java: 如果Java互操作很重要,您可以在case类中定义多个构造函数,这些构造函数将在Java中可见:

case class User(id: Option[Long], name: Option[String], date: Option[Date]) {
  def this(id: Long, name: String) = {
    this(Some(id), Some(name), None)
  }
}

One nice thing about Option[T] is that it has a safe default value None . Option[T]一个好处是它有一个安全的默认值None So initialise your vars to None instead of null . 因此,将您的变量初始化为None而不是null

You should also think about making your model class immutable. 您还应该考虑使您的模型类不可变。

More easy way to do this is 更简单的方法是这样做

case class User(id: Option[Long]=None, name: Option[String]=None, date: Option[Date]=None)

In this case if you give a value it takes the value or else it would take None as a default value. 在这种情况下,如果您给出一个值,它取值,否则它将取无值作为默认值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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