3
votes

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 ?

3
Where are you setting emailDir? You need to set its value in init - the-ginger-geek

3 Answers

5
votes

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.

3
votes

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("=============================================================")
}
0
votes

I'm supposing you using spring and his DI.

The problem is you caller the email field before make the instance and cannot inject the dependencies if not have any instance. For fix this issue, set dependency in constructor.

@Component
class Foo @Inject constructor(@param:Value("\${some.property}") val emailDir: String)
{
    init
    {
        log.info("=============================================================")
        log.info("Email Config File Dir: ${this.emailDir}")
        log.info("=============================================================")
     }
}