Andrey Hihlovskiy

Professional blog on groovy, gradle, Java, Javascript and other stuff.

Tag Archives: Language

Groovy language, spaceship operator

x <=> y

Useful in comparisons:

  • returns -1 if x is smaller than y
  • return 0 if x equals to y
  • returns 1 if x is greater than y.

Isn’t it sweet?

Groovy DSL == thermonuclear way of writing XML

import groovy.xml.MarkupBuilder

String createEAD(Closure closure) {
  def writer = new StringWriter()
  def xml = new MarkupBuilder(writer)
  xml.mkp.xmlDeclaration(version: '1.0', encoding: 'UTF-8')
  xml.'ead:ead'('xmlns:ead': 'urn:isbn:1-931666-22-9') {
    closure.delegate = new Object() {
      def text(Map attrs, content) {
        def a = attrs.keySet().find { it in ['bold', 'italic', 'underline'] }
        if(a && attrs[a]) {
          xml.'ead:emph' render: a, {
            text attrs.findAll({ it.key != a }), content
          }
        } else
          text content
      }
      def text(content) {
        if(content instanceof String)
          xml.mkp.yield content
        else if(content instanceof Closure)
          content()
      }
    }
    closure()
  }
  return writer.toString()
}

println createEAD {
  text bold: true, italic: true, {
    text 'Hello, '
    text underline: true, 'world!'
  }
}

expected output:

<?xml version='1.0' encoding='UTF-8'?>
<ead:ead xmlns:ead='urn:isbn:1-931666-22-9'>
  <ead:emph render='bold'>
    <ead:emph render='italic'>Hello, 
      <ead:emph render='underline'>world!</ead:emph>
    </ead:emph>
  </ead:emph>
</ead:ead>

Partial interface implementation in groovy

interface X {
  void a()
  void b()
}

class XAdapter implements X {
  void a() { println 'default implementation of a' }
  void b() { println 'default implementation of b' }
}

def o = [
  a: { println 'overridden implementation of a' }
] as XAdapter

o.a()
o.b()

will output:

overridden implementation of a
default implementation of b