https://kotlinlang.org logo
Title
b

bbaldino

12/06/2019, 9:44 PM
is it not possible to use a reference to a field in a companion object without using
.Companion
?
class Foo {
    companion object {
        val bar: Int = 42
    }
}
// Works
val member2 = Foo.Companion::bar
// Doesn't work: unresolved reference
val member = Foo::bar
k

karelpeeters

12/06/2019, 10:18 PM
There's pretty big difference between class member function references (type
KFunction0<R>
) and companion function references (type
KFunction1<Foo, R>
), maybe that's why it's not allowed.
m

Mike

12/06/2019, 11:08 PM
You could have a bar function on Foo class and in companion. How would compiler know which one? For that matter, how would you? Kotlin favours explicit definitions anyway.
b

bbaldino

12/06/2019, 11:09 PM
true, but java in that situation just errors on the ambiguity
but perhaps the inner workings of companion object make that difficult
m

Mike

12/06/2019, 11:41 PM
Or they intentionally show explicit mess over implicit?
e

E.Kisaragi

12/07/2019, 12:13 AM
I guess you’ll need Companion classifies if inside of it
b

bbaldino

12/07/2019, 12:14 AM
what do you mean?
e

E.Kisaragi

12/07/2019, 12:20 AM
Foo::bar corresponds Foo#bar which is instance property Foo::Companion::bar corresponds Foo.Companion#bar which is Companion’s property I guess Kotlin requires write Companion if it is in Companion?
b

bbaldino

12/07/2019, 12:21 AM
ah, yeah that's what i found...was just wondering if that was really the case (
.Companion
being required) or if i was missing something
e

E.Kisaragi

12/07/2019, 12:23 AM
But I think I misreading something — Java doesn’t require it, so Kotlin doesn’t either?
b

bbaldino

12/07/2019, 12:23 AM
Right, java doesn't...but Kotlin appears to.
e

E.Kisaragi

12/07/2019, 12:26 AM
But if Kotlin doesn’t, IDEA would give you a hint that unnecessary ‘Companion’ — I believe in builtin Kotlin support works, mmm