I have this piece of code that loads Properties from a file:
class Config {
val properties: Properties = {
val p = new Properties()
p.load(Thread.currentThread().getContextClassLoader.getResourceAsStream("props"))
p
}
val forumId = properties.get("forum_id")
}
This seems to be working fine.
I have tried moving the initialization of properties
into another val, loadedProperties
, like this:
class Config {
val properties: Properties = loadedProps
val forumId = properties.get("forum_id")
private val loadedProps = {
val p = new Properties()
p.load(Thread.currentThread().getContextClassLoader.getResourceAsStream("props"))
p
}
}
But it doesn't work! (properties
is null in properties.get("forum_id")
).
Why would that be? Isn't loadedProps
evaluated when referenced by properties
?
Secondly, is this a good way to initialize variables that require non-trivial processing? In Java, I would declare them final
fields, and do the initialization-related operations in the constructor.
Is there a pattern for this scenario in Scala?
Thank you!
lazy
to hedge initialization order issues can be convenient, but there are costs: 1) The accessor method is no longer a simple field retrieval (will they be inlined by HotSpot or other on-demand native code compilers?); 2) The accessor includes synchronization code; 3) Every instance requires a field holding the bits that encode the intialized status of eachlazy val
. – Herschel