Created
September 5, 2011 18:30
-
-
Save iainmcgin/1195622 to your computer and use it in GitHub Desktop.
Style-sheet like properties
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 UnitType extends Enumeration { | |
val Em = Value("em") | |
val Px = Value("px") | |
val Pc = Value("%") | |
} | |
import UnitType._ | |
case class Dimension( | |
val length : Double = 0.0, | |
val unit : UnitType.Value = Px) { | |
override def toString = "%.2f".format(length) + unit | |
} | |
case class Color( | |
val red : Double = 1.0, | |
val green : Double = 1.0, | |
val blue : Double = 1.0, | |
val alpha : Double = 1.0) { | |
override def toString = "#" + hex(red) + hex(green) + hex(blue) + hex(alpha) | |
def hex(x : Double) : String = "%02x".format((x * 255).toInt) | |
} | |
sealed abstract class Property[T](val name : String, val value : T) { | |
override def equals(other : Any) : Boolean = | |
other match { | |
case x : Property[_] => name == x.name | |
case _ => false | |
} | |
def +(other : Property[_]) : Set[Property[_]] = Set(this, other) | |
} | |
case class Width(v : Dimension = Dimension()) extends Property("width", v) | |
case class Height(v : Dimension = Dimension()) extends Property("height", v) | |
case class BackgroundColor(v : Color = Color()) extends Property("bgcolor", v) | |
val props : Set[Property[_]] = | |
Set( | |
Width(Dimension(15, Px)), | |
BackgroundColor(Color(0.5, 0, 0)), | |
Width(Dimension(20, Px)) | |
) | |
val props2 : Set[Property[_]] = | |
Width(Dimension(15)) + | |
Height(Dimension(100, Pc)) + | |
Height(Dimension(100, Px)) | |
println(props) | |
println(props2) | |
props foreach { | |
_ match { | |
case Width(x) => println("we have a width of " + x) | |
case other => println("we have another property: " + other.name + " -> " + other.value) | |
} | |
} | |
val bgcolor : Color = props2 collectFirst { case BackgroundColor(c) => c } getOrElse Color() | |
println("background color is " + bgcolor) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment