Created
May 14, 2015 09:12
-
-
Save btd/2e9e0eba3d5a6f39b859 to your computer and use it in GitHub Desktop.
Simple scala record
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
| package record | |
| class Col[T]( | |
| val name: String, | |
| private var value: Option[T] = None, | |
| private var initialValue: Option[T] = None | |
| ) { | |
| def apply(v: T): Unit = apply(v, false) | |
| def apply(v: Option[T]): Unit = apply(v, false) | |
| def apply(v: T, init: Boolean): Unit = apply(Option(v), init) | |
| def apply(v: Option[T], init: Boolean): Unit = { | |
| val processedValue = processValue(v) | |
| if(init) { | |
| initialValue = processedValue | |
| } | |
| value = processedValue | |
| } | |
| def get: Option[T] = value | |
| def dirty = value != initialValue | |
| override def toString = { | |
| s"Column[name=${name} value=${get} dirty=${dirty}]" | |
| } | |
| def processValue(v: Option[T]): Option[T] = v | |
| } | |
| class Rec { | |
| private var cols = Seq[Col[_]]() | |
| def columns = cols | |
| def col[T](name: String, defaultValue: => Option[T] = None): Col[T] = { | |
| addColumn[T](createColumn[T](name, defaultValue)) | |
| } | |
| def createColumn[T](name: String, defaultValue: Option[T]): Col[T] ={ | |
| new Col[T](name, defaultValue, None) | |
| } | |
| def addColumn[T](c: Col[T]): Col[T] = { | |
| cols = cols :+ c | |
| c | |
| } | |
| def dirty = cols.exists(_.dirty) | |
| override def toString = { | |
| val buf = new scala.collection.mutable.StringBuilder | |
| buf ++= "{ " | |
| buf ++= cols.view.map { c => | |
| s"${c.name}=${c.get.toString}" | |
| }.mkString(" ") | |
| buf ++= " }" | |
| buf.toString | |
| } | |
| def setOpt[T](c: this.type => Col[T], value: Option[T]): this.type = { | |
| c(this).apply(value) | |
| this | |
| } | |
| def set[T](c: this.type => Col[T], value: T): this.type = { | |
| c(this).apply(value) | |
| this | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment