Created
October 2, 2015 01:57
-
-
Save lloydmeta/e947a8f19b9edb585e6c to your computer and use it in GitHub Desktop.
NOTE: THIS IS NOT RECOMMENDED, just showing it is possible
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
object Player { | |
abstract class ReadOnlyPlayer extends Player { | |
override def hit(damage: Int) = this // This makes it "ReadOnly" | |
} | |
} | |
abstract class Player(private var _health: Int = 0) { mutablePlayer => | |
// Acts like a singleton with Health tied to the health of the mutable player | |
lazy val safeCopy = new Player.ReadOnlyPlayer { | |
override def health = mutablePlayer.health // forces the ReadOnly Player to always read from the health method of the mutable player | |
} | |
def health = _health | |
def play(players: List[Player.ReadOnlyPlayer]) = ()// how to denote inner type ReadOnlyPlayer ? | |
def hit(damage: Int) = { _health = Math.max(0, _health - damage); this } | |
} | |
val player = new Player(10){} | |
player.hit(1) | |
player.health // should be 9 | |
// Make a copy | |
val copy = player.safeCopy | |
assert(copy.health == 9) | |
player.hit(1) | |
assert(copy.health == 8) // in sync with Mutable | |
copy.hit(1) | |
assert(copy.health == 8) // unchanged |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment