Created
July 16, 2013 14:20
-
-
Save johnynek/6009156 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
class WriteOnce[T] { | |
private val ref = new java.util.concurrent.atomic.AtomicReference[Option[T]](None) | |
def init(t: T) { if(!ref.compareAndSet(None, Some(t))) sys.error("Already written"); } | |
def get: Option[T] = ref.get | |
} | |
scala> val w = new WriteOnce[Int] | |
w: WriteOnce[Int] = WriteOnce@215d55cb | |
scala> w.get | |
res4: Option[Int] = None | |
scala> w.init(42) | |
scala> w.get | |
res6: Option[Int] = Some(42) | |
scala> w.init(43) | |
java.lang.RuntimeException: Already written |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment