Delegates: Difference between revisions

Added Kotlin
(Added Kotlin)
Line 1,186:
document.write(a.operation() + "\n") ;
}</lang>
 
=={{header|Kotlin}}==
Whilst Kotlin supports class delegation 'out of the box', the delegate and delegator both have to implement a particular interface and the delegate cannot be optional or null.
 
The first two scenarios are not therefore strictly possible though the second can be simulated by passing a 'responds' parameter to the delegate class constructor.
<lang scala>// version 1.1.51
 
interface Thingable {
fun thing(): String?
}
 
class Delegate(val responds: Boolean) : Thingable {
override fun thing() = if (responds) "delegate implementation" else null
}
 
class Delegator(d: Delegate) : Thingable by d {
fun operation() = thing() ?: "default implementation"
}
 
fun main(args: Array<String>) {
// delegate doesn't respond to 'thing'
val d = Delegate(false)
val dd = Delegator(d)
println(dd.operation())
 
// delegate responds to 'thing'
val d2 = Delegate(true)
val dd2 = Delegator(d2)
println(dd2.operation())
}</lang>
 
{{out}}
<pre>
default implementation
delegate implementation
</pre>
 
=={{header|Logtalk}}==
9,490

edits