Is it possible to call an extension function on cl...
# announcements
b
Is it possible to call an extension function on class A, defined in class B, from outside of class B? i.e.:
Copy code
class B {
   fun Int.answer(): Int { return 42 }
}
and somewhere else be able to do something like:
Copy code
fun main() {
        val myB = B()
        val num: Int = 10
        num.apply {
            myB.answer()
        }
}
My quick test tells me no, but is it imposible/nonsensical or am I just invoking it wrong? I want to be able to implement a function on some type A using some state from an instance of type B.
s
Copy code
fun main() {
        val myB = B()
        val num: Int = 10
        myB.apply {
            num.answer()
        }
}
or, more idiomatic:
Copy code
fun main() {
        val myB = B()
        val num: Int = 10
        with (myB) {
            num.answer()
        }
}
👍 3
b
Ah ha! Thanks!
s
Using
with
you can read it like this: In the context (with context) of
myB
call
answer()
on the provided
Int
☝️ 1
b
Yeah, makes sense
s
The
apply
is usually used for applying changes to the receiver of the `apply`…. 🙂
t
run
should be more suitable in this case