Groovy equivalent to Scala trait stackable modifications? -
i have been going through programming scala book(by martin odersky,lex spoon,bill venners ed1) , came across traits. section find interesting stackable modifications. example used
abstract class intqueue { def get(): int def put(x: int) } trait incrementing extends intqueue { abstract override def put(x: int) {super.put(x+1)} } trait filtering extends intqueue{ abstract override def put(x: int){ if(x >=0) super.put(x) } }
so example provided has concrete class "basicintqueue extends intqueue follows
import scala.collection.mutable.arraybuffer class basicintqueue extends intqueue{ private val buf = new arraybuffer[int] def get() = buf.remove(0) def put(x: int) {buf +=x} }
scala> val queue = (new basicintqueue incrementing filtering)
scala> queue.put(-1);queue.put(0);queue.put(1)
scala> queue.get() = 1
so example shows both filtering , incrementing "chained" , executed before elements "put" queue.
i wondering how accomplished in groovy. maybe not needed because of groovy's meta-programability.
groovy doesn't have natural way stackable traits. categories provide of trait functionality, they're not suited overriding methods , can't stacked without metaclass magic.
a better approach in groovy apply decorator pattern along @delegate
annotation. each "trait" can override appropriate behavior , delegate "super" class. example:
interface intqueue { def get() def put(x) } class incrementing implements intqueue { @delegate intqueue self def put(x) { self.put(x+1) } } class filtering implements intqueue { @delegate intqueue self def put(x) { if (x >= 0) { self.put(x) } } } class basicintqueue implements intqueue { private buf = [] def get() { buf.pop() } def put(x) { buf << x } }
you construct object desired traits so:
def q = new filtering(self: new incrementing(self: new basicintqueue()))
Comments
Post a Comment