280
CHAPTER 10: Development
or write more complex constructs using method calls and lambda functions:
val s = "8 + 1 is: ${ { i: Int -> i + 1 }(8) }"
Qualified “this”
If this is not what you want but you instead want to refer
to this from an outer context, in
Kotlin you use the @ qualifier as follows:
class A {
val b = 7
init {
val p = arrayOf(8,9).apply {
this[0] += this@A.b
}
...
}
}
Delegation
Kotlin allows for easily following the delegation pattern. Here’s an example:
interface Printer {
fun print()
}
class PrinterImpl(val x: Int) : Printer {
override fun print() { print(x) }
}
class Derived(b: Printer) : Printer by b
Here, the class Derived is of type Printer and delegates all its method calls to the b object.
So, you can write the following:
val pi = PrinterImpl(7)
Derived(pi).print()
You are free to
overwrite method calls at will, so you can adapt the delegate to use new
functionalities.
class Derived(val b: Printer) : Printer by b {
override fun print() {
print("Printing:")
b.print()
}
}