Delegates: Difference between revisions
Content added Content deleted
(Added Julia language) |
(Scala contribution added.) |
||
Line 2,083: | Line 2,083: | ||
</lang> |
</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}}== |
=={{header|Sidef}}== |
||
<lang ruby>class NonDelegate { } |
<lang ruby>class NonDelegate { } |
||
Line 2,110: | Line 2,144: | ||
say "Delegate: #{d.operation}"</lang> |
say "Delegate: #{d.operation}"</lang> |
||
{{out}} |
{{out}} |
||
empty: default implementation |
|||
<pre> |
|||
NonDelegate: default implementation |
|||
Delegate: delegate implementation |
|||
⚫ | |||
</pre> |
|||
=={{header|Swift}}== |
=={{header|Swift}}== |