UNRESOLVED_REFERENCE未解析的参考:isInitialized [英] UNRESOLVED_REFERENCE Unresolved reference: isInitialized
问题描述
我正在尝试使用Kotlin的检查Lateinit属性状态的新功能,但出现此编译时错误Unresolved reference: isInitialized
I'm trying to use Kotlin's new feature of checking lateinit property status, but got this compile time error Unresolved reference: isInitialized
我已经用kotlin版本的kotlin_version = '1.2.0-beta-31'
配置了build.gradle文件(android studio版本是3.0)
并更新了相同版本的kotlin插件.
这是我的代码段,我在其中使用isInitialized
检查.
I have configure my build.gradle file with kotlin version of kotlin_version = '1.2.0-beta-31'
(android studio version is 3.0)
and also updated kotlin plugin with same version.
this is my code snippet, where I'm using isInitialized
check.
还包含一个反射库
compile group: 'org.jetbrains.kotlin', name: 'kotlin-reflect', version: '1.2.0-beta-31'
.
lateinit var k: SomeObjectType
fun instance(): SomeObjectType {
if (::k.isInitialized) {
k = SomeObjectType()
}
return k
}
推荐答案
This is a bug as reported here and is released in v1.2-rc-1
更新:Kotlin 1.2 RC似乎可以使用"1.2.0-rc-39",因此,如果您更新插件并使用此版本,则应解决此问题.
Update: Kotlin 1.2 RC appears to be available as '1.2.0-rc-39', so if you update your plugin and use this version, your issue should be resolved.
作为解决方法,直到安装rc-1,如在此项目中所示,在变量前加上this::
即可.
As a workaround until you install rc-1, prefixing the variable with this::
works as can be shown in this project.
package com.example.john.so2
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
data class SomeObjectType(val value: String)
lateinit var k: SomeObjectType
class MainActivity : AppCompatActivity() {
lateinit var k: SomeObjectType
fun instance(): SomeObjectType {
if (this::k.isInitialized) {
return k
} else {
return SomeObjectType("k was not initialized")
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
println("instance = ${instance()}")
k = SomeObjectType("k was initialized")
println("instance = ${instance()}")
}
}
产生:
11-03 19:31:14.496 31982-31982/com.example.john.so2 I/System.out: instance = SomeObjectType(value=k was not initialized)
11-03 19:31:14.496 31982-31982/com.example.john.so2 I/System.out: instance = SomeObjectType(value=k was initialized)
顺便说一句,我留下了我原来的答案,因为它突出了正确的语法在"try-online"中有效的事实
BTW, I left my original answer as it highlights the fact that the correct syntax works in "try-online"
这篇关于UNRESOLVED_REFERENCE未解析的参考:isInitialized的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!