Any one have similar problem before?
How can we declare a default variable value for init()?
Below is my code sample,
@Value("\${app.email-config-file: D:\\email\\src\\main\\resources\\email.config}")
private lateinit var emailDir: String
init {
log.info("====================================================================================================")
log.info("Email Config File Dir: ${this.emailDir}")
log.info("====================================================================================================")
}
Then below exception throw :
Caused by: kotlin.UninitializedPropertyAccessException: lateinit property emailDir has not been initialized
Any solution can share ?
Kotlin lateinit var properties cannot be accessed before the value is actually set, and the UninitializedPropertyAccessException is thrown in that case.
From what I see in your code, you expect the property value to be set by a framework (Spring?) based on the @Value annotation. But you access the property in the init block, which is executed at the object construction time, and I'm quite sure, the framework sets the values only after the object is constructed.
You can either avoid using the property value before it is set (don't use it in the init blocks and other property initializers) or provide a default value for the property, as in @wasyl's answer.
How can we declare a default variable value for init()?
Once you have a default value, the property doesn't have to be marked as lateinit. So you would simply do:
@Value("\${app.email-config-file: D:\\email\\src\\main\\resources\\email.config}")
private var emailDir: String = "someDirectory/"
init {
log.info("=============================================================")
log.info("Email Config File Dir: ${this.emailDir}")
log.info("=============================================================")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With