Last active
October 11, 2017 16:51
-
-
Save Megamiun/778234b1bb7c9bf3e9fceb6f25264ecd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// It seems that a Delegate Class always forwards to the same instance that it was created with. | |
// But it opens a possible misunderstanding: If I declare the delegated instance in the constructor | |
// as a var, shouldn't it change behaviour when the var changes? Or shouldn't a delegated instance | |
// always be a val, so it can't be changed? I think I prefer the first, as it would give the user more choice. | |
// General Interface | |
interface Context { | |
fun print(printable: String) | |
} | |
// Basic Implementation of Context, just prints to console the same data | |
class BasicContext : Context { | |
override fun print(printable: String) { | |
System.out.println(printable) | |
} | |
} | |
// Basic Implementation of Context, just prints to console with quotes | |
class QuotedContext : Context { | |
override fun print(printable: String) { | |
System.out.println("\"$printable\"") | |
} | |
} | |
// Delegated Context, doesn't change context on call | |
class DelegatedContextWrapper(private var context: Context = BasicContext()) : Context by context { | |
fun changeContext(context: Context) { | |
this.context = context | |
} | |
} | |
fun main(args: Array<String>) { | |
val printable = "It's Alive!" | |
val context = DelegatedContextWrapper() | |
// Print the same way | |
context.print(printable) | |
// Changes to Quotable Context | |
context.changeContext(QuotedContext()) | |
// Should print in quotes, isn't | |
context.print(printable) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment