Skip to content

Instantly share code, notes, and snippets.

@johnynek
Created July 16, 2013 14:20
Show Gist options
  • Save johnynek/6009156 to your computer and use it in GitHub Desktop.
Save johnynek/6009156 to your computer and use it in GitHub Desktop.
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