(Kotlin) lateinit 属性“VAL 变量”尚未初始化

Cha*_*ang 3 kotlin

以前有人遇到过类似的问题吗?

我们如何为 init() 声明一个默认变量值?

下面是我的代码示例,

@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("====================================================================================================")
}
Run Code Online (Sandbox Code Playgroud)

然后在异常抛出以下:

引起:kotlin.UninitializedPropertyAccessException:lateinit 属性 emailDir 尚未初始化

有什么解决方案可以分享吗?

hot*_*key 5

在实际设置值之前无法访问Kotlinlateinit var属性UninitializedPropertyAccessException在这种情况下会抛出 。

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.