Skip to content

Instantly share code, notes, and snippets.

@timyates
Last active October 21, 2015 04:25
Show Gist options
  • Save timyates/10257468 to your computer and use it in GitHub Desktop.
Save timyates/10257468 to your computer and use it in GitHub Desktop.
Messing with groovy traits
// Bad example of @ForceOverride... enjoy! (?)
import groovy.transform.*
class BasicIntQueue extends LinkedList<Integer> {
Integer get() {
this.poll()
}
void put( Integer x ) {
this.offer( x )
}
}
// Quick test
def queue = new BasicIntQueue()
queue.put( 10 )
queue.put( 20 )
assert queue.get() == 10
assert queue.get() == 20
// Then define a trait that forcibly overrides the class implemntation of put
trait Doubling implements Queue<Integer> {
@ForceOverride
void put( Integer x ) {
this.offer( x * 2 )
}
}
// Quick instance
class DoubleQueue extends BasicIntQueue implements Doubling {
}
// And a quick test
def queue2 = new DoubleQueue()
queue2.put( 10 )
assert queue2.get() == 20
import groovy.transform.*
trait QueuePut<T> implements Queue<T> {
T get() { poll() }
void put( T v ) { offer( v ) }
}
class BasicIntQueue extends LinkedList<Integer> implements QueuePut<Integer> {}
def queue = new BasicIntQueue()
queue.put( 10 )
queue.put( 20 )
assert queue.get() == 10
assert queue.get() == 20
// Then define a trait that forcibly overrides the class implemntation of put
trait Doubling implements Queue<Integer> {
@ForceOverride
void put( Integer x ) {
this.offer( x * 2 )
}
}
// Quick instance
class DoubleQueue extends BasicIntQueue implements Doubling {}
// And a quick test
def queue2 = new DoubleQueue()
queue2.put( 10 )
queue2.put( 20 )
assert queue2.get() == 20
assert queue2.get() == 40
@Grab('org.slf4j:slf4j-api:1.6.1')
@Grab('ch.qos.logback:logback-classic:0.9.28')
import org.slf4j.*
import groovy.transform.*
trait Loggable {
@Memoized getLog() {
LoggerFactory.getLogger( this.getClass() )
}
}
class Test implements Loggable {
def foo() {
log.debug( 'Woo. In foo' )
}
}
class Test2 implements Loggable {
def bar() {
log.info( 'Ha. In bar' )
}
}
new Test().foo()
new Test2().bar()
import groovy.transform.*
@CompileStatic
trait IgnoredRemovable {
void remove() {}
}
@CompileStatic
trait Endless {
boolean hasNext() { true }
}
@CompileStatic
trait EndlessIterator<T> implements IgnoredRemovable, Endless, Iterator<T> {
T value
T next() { value }
}
@CompileStatic
class LoadsOfOnes implements EndlessIterator<Integer> {
LoadsOfOnes() {
value = 1
}
}
assert new LoadsOfOnes().take( 5 ).collect() == [ 1, 1, 1, 1, 1 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment