Scala - initialization order of vals

允我心安 提交于 2019-11-27 15:09:19

Vals are initialized in the order they are declared (well, precisely, non-lazy vals are), so properties is getting initialized before loadedProps. Or in other words, loadedProps is still null when propertiesis getting initialized. The simplest solution here is to define loadedProps before properties:

class Config {
  private val loadedProps = {
    val p = new Properties()
    p.load(Thread.currentThread().getContextClassLoader.getResourceAsStream("props"))
    p 
  }
  val properties: Properties = loadedProps
  val forumId = properties.get("forum_id")
}

You could also make loadedProps lazy, meaning that it will be initialized on its first access:

class Config {
  val properties: Properties = loadedProps
  val forumId = properties.get("forum_id")

  private lazy val loadedProps = {
    val p = new Properties()
    p.load(Thread.currentThread().getContextClassLoader.getResourceAsStream("props"))
    p 
  }
}

Using lazy val has the advantage that your code is more robust to refactoring, as merely changing the declaration order of your vals won't break your code.

Also in this particular occurence, you can just turn loadedProps into a def (as suggested by @NIA) as it is only used once anyway.

I think here loadedProps can be simply turned into a function by simply replacing val with def:

private def loadedProps = {
  // Tons of code
}

In this case you are sure that it is called when you call it.

But not sure is it a pattern for this case.

Just an addition with a little more explanation:

Your properties field initializes earlier than loadedProps field here. null is a field's value before initialization - that's why you get it. In def case it's just a method call instead of accessing some field, so everything is fine (as method's code may be called several times - no initialization here). See, http://docs.scala-lang.org/tutorials/FAQ/initialization-order.html. You may use def or lazy val to fix it

Why def is so different? That's because def may be called several times, but val - only once (so its first and only one call is actually initialization of the fileld).

lazy val can initialize only when you call it, so it also would help.

Another, simpler example of what's going on:

scala> class A {val a = b; val b = 5}
<console>:7: warning: Reference to uninitialized value b
       class A {val a = b; val b = 5}
                        ^
defined class A

scala> (new A).a
res2: Int = 0 //null

Talking more generally, theoretically scala could analize the dependency graph between fields (which field needs other field) and start initialization from final nodes. But in practice every module is compiled separately and compiler might not even know those dependencies (it might be even Java, which calls Scala, which calls Java), so it's just do sequential initialization.

So, because of that, it couldn't even detect simple loops:

scala> class A {val a: Int = b; val b: Int = a}
<console>:7: warning: Reference to uninitialized value b
       class A {val a: Int = b; val b: Int = a}
                             ^
defined class A

scala> (new A).a
res4: Int = 0

scala> class A {lazy val a: Int = b; lazy val b: Int = a}
defined class A

scala> (new A).a
java.lang.StackOverflowError

Actually, such loop (inside one module) can be theoretically detected in separate build, but it won't help much as it's pretty obvious.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!