Created
March 18, 2013 10:32
-
-
Save markhibberd/5186275 to your computer and use it in GitHub Desktop.
Attempt at something to constrain setting of var. Still requires a significant amount of discipline to ensure var does not escape, but
at least you can make sure (potentially large) parts of your system can not set the
var. Not quite, set once, but if you have a specific flow it can sometimes help. Can be extended to ensure var is only read when…
This file contains hidden or 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 IsEmpty | |
| class Holder[A, B](private var value: A) { | |
| def set(a: A)(implicit ev: B =:= IsEmpty.type) { | |
| value = a | |
| } | |
| } | |
| object Holder { | |
| def empty[A]: Holder[A, IsEmpty.type] = | |
| new Holder[A, IsEmpty.type](null.asInstanceOf[A]) | |
| def full[A](a: A): Holder[A, Nothing] = | |
| new Holder[A, Nothing](a) | |
| } | |
| object Example extends App { | |
| def somePartOfSystem(h: Holder[Int, _]) { | |
| // doesn't compile | |
| // h.set(1) | |
| } | |
| def somePartOfSystemThatKnowsItIsNotSet(h: Holder[Int, IsEmpty.type]) { | |
| // does compile | |
| h.set(1) | |
| } | |
| somePartOfSystem(Holder.empty[Int]) | |
| somePartOfSystemThatKnowsItIsNotSet(Holder.empty[Int]) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment