Anonymous user
Delegates: Difference between revisions
Scala contribution added.
(Added Julia language) |
(Scala contribution added.) |
||
Line 2,083:
</lang>
=={{header|Scala}}==
{{Out}}Best seen running in your browser either by [https://scalafiddle.io/sf/cCYD9tQ/0 ScalaFiddle (ES aka JavaScript, non JVM)] or [https://scastie.scala-lang.org/2TWYJifpTuOVhrAfWP51oA Scastie (remote JVM)].
<lang Scala>trait Thingable {
def thing: String
}
class Delegator {
var delegate: Thingable = _
def operation: String = if (delegate == null) "default implementation"
else delegate.thing
}
class Delegate extends Thingable {
}
// Example usage
// Memory management ignored for simplification
object DelegateExample extends App {
val a = new Delegator
assert(a.operation == "default implementation")
// With a delegate:
val d = new Delegate
a.delegate = d
assert(a.operation == "delegate implementation")
// Same as the above, but with an anonymous class:
a.delegate = new Thingable() {
override def thing = "anonymous delegate implementation"
}
assert(a.operation == "anonymous delegate implementation")
}</lang>
=={{header|Sidef}}==
<lang ruby>class NonDelegate { }
Line 2,110 ⟶ 2,144:
say "Delegate: #{d.operation}"</lang>
{{out}}
empty: default implementation
▲Delegate: delegate implementation
=={{header|Swift}}==
|