Skip to content

Instantly share code, notes, and snippets.

@stephenh
Created November 30, 2009 06:45
Show Gist options
  • Save stephenh/245296 to your computer and use it in GitHub Desktop.
Save stephenh/245296 to your computer and use it in GitHub Desktop.
import scala.collection.mutable.ListBuffer
object PropertyObjectsTest {
def main(args: Array[String]): Unit = {
// First using explicit get/set methods
val p1 = new Parent
p1.name.set("Bob")
println(p1.name.get)
val c1 = new Child
c1.name.set("Junior")
p1.children.get += c1
for (c <- p1.children.get) {
println(c.name.get)
}
// Now with spiffy implicit and := operator
val p2 = new Parent
p2.name := "Bob"
println(p2.name)
val c2 = new Child
c2.name := "Junior"
p2.children += c2
for (c <- p2.children) {
println(c.name)
}
}
}
// Domain objects
class Parent {
val name = new StringProperty
val children = new ListProperty[Child]
}
class Child {
val name = new StringProperty
}
// Property trait, companion object, and implementations
/** PropertyObject interface for getting/setting values. */
trait Property[T] {
/** @return the current value */
def get: T
/** @param value the new value */
def set(value: T)
/** @param value the new value via a ':=' operator */
def :=(value: T)
}
/** Companion object to the Property trait. */
object Property {
/** Implicitly called to convert Property[T] -> T */
implicit def p2value[T](p: Property[T]): T = p.get
// E.g.:
// parent.name.endsWith("a")
// Transparently becomes:
// parent.name.get().endsWith("a")
}
/** Simple base class for XxxProperty classes. */
abstract class AbstractProperty[T] extends Property[T] {
var value: T
def get = value
def set(value: T) = this.value = value
def :=(value: T) = set(value)
override def toString = this.getClass.getSimpleName+"[" + value + "]"
}
/** Wraps a string. */
class StringProperty extends AbstractProperty[String] {
override var value: String = null
}
/** Wraps a list. */
class ListProperty[U] extends AbstractProperty[ListBuffer[U]] {
override var value: ListBuffer[U] = new ListBuffer
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment