1

If I have an extension function for type A declared inside class B:

class A

class B {
    fun A.foo() = "Hello"
}

Can I call this function at all from code that is outside class B?

val a = A()
val b = B()
a.foo()      // error: unresolved reference: foo
b.foo()      // error: unresolved reference: foo
Tobia
  • 17,856
  • 6
  • 74
  • 93
  • This code doesn't even look like it will compile. Granted, I'm not a Kotlin expert, but... maybe you could show a bit more code? Does Kotlin have access modifiers you've forgotten to include? – Robert Harvey Mar 21 '19 at 14:09
  • @RobertHarvey the first part will definitely compile. The second part won't since the extension method `A.foo` isn't in the global scope like the error says. – FHTMitchell Mar 21 '19 at 14:36
  • @RobertHarvey the only part that doesn't compile is where I said there would be errors: https://play.kotlinlang.org/#eyJ2ZXJzaW9uIjoiMS4zLVJDIiwicGxhdGZvcm0iOiJqYXZhIiwiYXJncyI6IiIsIm5vbmVNYXJrZXJzIjp0cnVlLCJ0aGVtZSI6ImlkZWEiLCJmb2xkZWRCdXR0b24iOnRydWUsInJlYWRPbmx5IjpmYWxzZSwiY29kZSI6ImNsYXNzIEFcblxuY2xhc3MgQiB7XG4gICAgZnVuIEEuZm9vKCkgPSBcIkhlbGxvXCJcbn1cblxudmFsIGEgPSBBKClcbnZhbCBiID0gQigpXG5hLmZvbygpXG5iLmZvbygpIn0= – Tobia Mar 21 '19 at 16:30

2 Answers2

4

Yes:

with(b) { 
    a.foo() 
} 

Other functions accepting a lambda with a B receiver would work as well.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
0

No, when you've defined A.foo inside B, you've effectively scoped the function to the class. However, you can always move it outside the class... functions can be top-level also :)