I have the following code:
fun process(call: () -> Int) {
}
fun aa() = 5
class A {
companion object Factory {
fun bb() = 6
}
}
fun test() {
process(::aa) // OK
process(::A.bb) // Overload resolution ambiguity
}
When I try to call process(::A.bb)
I get the following error:
Error:Overload resolution ambiguity:
public constructor A() defined in ru.netimen.hitch_hikingstats.A
public companion object Factory defined in ru.netimen.hitch_hikingstats.A
Is there any way to reference companion object methods?
In some languages like Java and C#, we use static keyword to declare the members of the class and use them without making any object i.e. just call them with the help of class name. So, to call a method named myMethod() having a class name as MyClass , we will use: MyClass. myMethod();
Object declarations are very useful for implementing the Singleton pattern. And the getInstance method can then be invoked like this. A companion object is a specific type of object declaration that allows an object to act similar to static objects in other languages (such as Java).
Now it's possible for companion object. Note that the data class does not implement the interface, but its companion object does. 2- you can define extension functions on it. you can call these extension functions as functions on class name.
companion object is how you define static variables/methods in Kotlin. You are not supposed to create a new instance of Retrofit / ApiService each time you execute a request, however.
In Kotlin 1.4+ you can use process(A::bb)
.
In 1.1.2+ you can use process(A.Factory::bb)
or process((A)::bb)
.
Not so long after this question was asked Kotlin 1.1 was released with support for bound callable references:
Kotlin 1.1.2 came with a fix for KT-15951, meaning that since then you can call process(A.Factory::bb)
.
There is also KT-13934 targeted for Kotlin 1.4, to support process(A::bb)
.
Syntactically it would be A.Factory:bb
but it will not work. At first, bb
is a A.Factory.() -> Int
while () -> Int
is required.
Secondly, callable references to object members are not supported at the moment as the Kotlin compiler says. Here's a parent task for all callable members tasks: https://youtrack.jetbrains.com/issue/KT-1183.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With