Skip to content

Seriously Use Groovy NOW

Andrew Serff edited this page Nov 21, 2015 · 1 revision

HOME > [NFJS 2015](NFJS 2015) > [Seriously Use Groovy Now](Seriously Use Groovy Now)

Ken Kousen https://github.com/kousen/use_groovy_now

There is no reason not so start using Groovy now if you are using Java. Groovy doesn’t try to replace Java, just add to it.

groovy-lang.org

Groovy is now a top level Apache project (as of like yesterday)

###Groovy EcoSystem

  • Grails
  • Gradle
  • Spock - Test framework
  • Geb - Browser automation
  • Griffon - Grails for Desktop Apps
  • GPars - Groovy Parallel systems

Groovy has optional typing You can say:

  • String url = ‘http://thing.com'
  • def url = ‘http://thing.com'
  • def things = “these are some strings”.split()
  • List things = “these are some strings”.split()
  • def things = “these are some strings”.split() as ArrayList
  • def things = “these are some strings”.split() as SortedSet

Groovy wil execute source files: groovy hello_world.groovy

To add Groovy: You have to build with Groovy, but all you need is to add the groovy-all.jar

###Operator overloading All operations are done as a BigDecimal in Groovy In java 3/4 = 1 - Integer division In Groovy 3/4 = .75 - BigDecimal division

String s = ‘this is a string'
s[2] = i
s[0..3] = this
s[-1] = g

== calls .equals() in Groovy

###POGOs

class Person {
   String first
   String last
}

Person p = new Person()
p.setFirst(‘John’)
p.last = ‘Elway'
println “${p.getFirst()} ${p.last}”   - Note that double quote means evaluate as groovy.

In groovy, the default is private if you don’t specify for a class/member var. default is public for methods.

groovy gives you default constructor, but it also gives you a map based constructor:

Person p = new Person(first: ‘John’, last: ‘Elway’)

This calls the default constructor and then calls the setters.

String toString() { “$first $last” } - no return, no {} if just a var to evaluate.

import groovy.transform.*

@ToString
class Person {
     String first
     String last
}

Generates a toString that would output: Person(John, Elway)

@Canonical - gives you the @ToString, @EqualsAndHashCode, and @TupleConstructor

def nums = [3,1,4,5,9]
nums.each { n -> println n }
nums.each { println it } - if you give no dummy var, the default is “it"

nums.eachWithIndex { n, idx -> println “nums[$idx] == $n” }

int total = nums.sum();
int total = nums.collect {
  it * 2
}.findAll {
     it % 3 == 0
}.sum()
def map = [a:1, b:2, c:3];
map.each { e -> prinln “map[$e.key] = $e.value" }
map.each { k,v -> println “$k = $v” }
String base = ‘https://maps.googleapis.com/maps/api/geocode/xml?'
def encoded = [‘10345 Park Meadows Drive’, ‘Lonetree’, ‘CO’].collect {
  URLEncoder.encode(it, ‘UTF-8’)
}.join(‘,’)
String qs = “address=$encoded"
def root = new XmlSluper().parse(“$base$qs”)
def loc = root.geometry[0].location
println “(${loc.lat},${loc.lng})"

Three single quotes is a multi-line string Three double quotes is a multi-line interpolated string

File f = new File(‘mayflies.txt’).text - get the contents as a String.

f << “some new text” - write to file

Builders

def builder = new MarkupBuilder()
builder.people {
   person(id:1) {
      name 'Buffy'
   }
   person(id: 2) {
     name ‘Willow'
   }
}

would output an XML document of:

<people>
<person id=1><name>Buffy</name></person>
<person id=2><name>Willow</name></person>
</people>

There is a UI builder (SwingBuilder), JSON builder, etc.

Clone this wiki locally