bbaldino
07/09/2020, 5:59 PMclass B {
fun Int.answer(): Int { return 42 }
}
and somewhere else be able to do something like:
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.streetsofboston
07/09/2020, 6:01 PMfun main() {
val myB = B()
val num: Int = 10
myB.apply {
num.answer()
}
}
or, more idiomatic:
fun main() {
val myB = B()
val num: Int = 10
with (myB) {
num.answer()
}
}
bbaldino
07/09/2020, 6:01 PMstreetsofboston
07/09/2020, 6:04 PMwith
you can read it like this: In the context (with context) of myB
call answer()
on the provided Int
bbaldino
07/09/2020, 6:04 PMstreetsofboston
07/09/2020, 6:05 PMapply
is usually used for applying changes to the receiver of the `apply`…. 🙂tseisel
07/10/2020, 8:36 AMrun
should be more suitable in this case