Sunday, 1 September 2013

Scala Dynamics: Ability to add dynamic methods?

Scala Dynamics: Ability to add dynamic methods?

I know I can add dynamic "fields" like this:
import collection.mutable
class DynamicType extends Dynamic {
private val fields = mutable.Map.empty[String, Any].withDefault {key =>
throw new NoSuchFieldError(key)}
def selectDynamic(key: String) = fields(key)
def updateDynamic(key: String)(value: Any) = fields(key) = value
def applyDynamic(key: String)(args: Any*) = fields(key)
}
I can then do stuff like this:
val foo = new DynamicType
foo.age = 23
foo.name = "Rick"
But, I want to extend this one step farther and add dynamic methods e.g:
foo.greet = (name: String) => s"Nice to meet you $name, my name is
${this.name}"
foo.greet("Nat"); //should return "Nice to meet you Nat, my name is Rick"
I tried storing all methods in separate map in updateDynamic but I could
not figure out a generic way to handle the arity problem. So is there a
way to use Macros + Dynamics to have something like this?

No comments:

Post a Comment