Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Attributes With Path-Dependent Types
trait AttributeName { self =>
type AttributeType
def of(value : AttributeType) : Attribute = new Attribute {
type Name = self.type
val Value = value
}
}
trait Attribute {
type Name <: AttributeName
def Value : Name#AttributeType
}
case object Health extends AttributeName {
type AttributeType = Int
}
case object Name extends AttributeName {
type AttributeType = String
}
class Attributes {
val _map = scala.collection.mutable.Map[AttributeName, Attribute]()
def get(key : AttributeName) : key.AttributeType = {
_map(key).Value.asInstanceOf[key.AttributeType]
}
def add(key : AttributeName, attr : Attribute) = {
_map(key) = attr
}
}
val attrs = new Attributes
attrs.add(Health, Health of 3)
attrs.add(Name, Name of "Foo")
val health : Int = attrs.get(Health)
val name : String = attrs.get(Name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment