dsl - Scala: store call-by-name variable as class field -
in progress in scala learning try implement simple dsl callbacks
object button {...} // apply class button(val name: string) { private val: => unit; // doesn't work def click(f: => unit) = { _click_cb = f } def onclick() = this._click_cb() } button("click me!") click {println("clicked!")}
i create new object, pass callback store. demo framework fires onclick
method, should call stored one
it works () => unit
dsl looks ugly:
button("click me!") click (() => println("clicked!"))
sure, onclick
abstract , implement anonymous class later
new button("click me!") {def onclick = println("clicked!")}
but want play dsl , such
the questions are:
- how store
f
in_click_cb
? - how provide initial "empty" function
_click_cb
? - and maybe there's more scala-way achieve this? (without anonymous classes)
an uglier version show lazy val can hold name parameter value without evaluating it:
case class button(val name: string) { def clickcallback(): unit = () def click(f: => unit) = { lazy val notevaluated = f new button(name) { override def clickcallback() = notevaluated } } def onclick(): unit = clickcallback() }
a cleaner , more functional implementation:
class button(val name: string) { def click(f: => unit) = new button(name) { override def onclick() = f } def onclick(): unit = () }
Comments
Post a Comment