Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UNRESOLVED_REFERENCE Unresolved reference: isInitialized

Tags:

android

kotlin

I'm trying to use Kotlin's new feature of checking lateinit property status, but got this compile time error Unresolved reference: 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.

also had a reflect library included

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
}
like image 698
jemo mgebrishvili Avatar asked Nov 01 '17 09:11

jemo mgebrishvili


1 Answers

This is a bug as reported here and is released in v1.2-rc-1

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.

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


}

which yields:

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)

BTW, I left my original answer as it highlights the fact that the correct syntax works in "try-online"

like image 116
nPn Avatar answered Oct 27 '22 18:10

nPn