Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overload resolution ambiguity. All these functions match

Tags:

kotlin

I tried to check, lateinit variable is initialized or not in a function using reference operator. The function name and variable name is same in this case. So that Kotlin throws

Overload resolution ambiguity. All these functions match

exception. Actually what's wrong in this code?

class ABC

class MyClass {
    private lateinit var abc: ABC

    fun abc() {
        if(!::abc.isInitialized){
            println("Hello")
        }
    }
}
like image 549
JEGADEESAN S Avatar asked Feb 15 '18 10:02

JEGADEESAN S


2 Answers

You can disambiguate the reference by extracting a variable and explicitly specifying its type:

class ABC

class MyClass {
    private lateinit var abc: ABC

    fun abc() {

        val abc: KProperty0<ABC> = ::abc
        if(!abc.isInitialized){
            println("Hello")
        }
    }
}
like image 162
adk Avatar answered Nov 11 '22 01:11

adk


It's a simple name clash. The compiler does not know whether you're referring to the method abc or the property abc. A renaming fixes the problem:

class MyClass {
    private lateinit var abc: ABC

    fun abcFun() {
        val prop = this::abc
        if (!::abc.isInitialized) {
            println("Hello")
        }
    }
}
like image 6
s1m0nw1 Avatar answered Nov 11 '22 00:11

s1m0nw1