Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Kotlin) lateinit property 'VAL variable' has not been initialized

Tags:

kotlin

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 ?

like image 326
Kim Avatar asked Oct 27 '25 23:10

Kim


2 Answers

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.

like image 170
hotkey Avatar answered Oct 29 '25 15:10

hotkey


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("=============================================================")
}
like image 44
wasyl Avatar answered Oct 29 '25 14:10

wasyl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!