Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Groovy 101

Avatar for jflorencio jflorencio
September 27, 2012

Groovy 101

Avatar for jflorencio

jflorencio

September 27, 2012
Tweet

Other Decks in Programming

Transcript

  1. == is Actually Useful assert "hi world" == ("hi" +

    " world") assert [1, 2, 3] == [1, 2, 3] assert ![1, 2, 3].is([1,2,3]) assert null != [1, 2, 3]
  2. Properties class Foo { String bar } def f =

    new Foo() f.bar = "hi" assert "hi" == f.bar assert "hi" == f.getBar() f.setBar("hello") assert "hello" == f.bar
  3. Groovy Beans class Profile { String name, company } def

    p = new Profile( name: "Joe", company: "LinkedIn") assert "Joe" == p.name assert "LinkedIn" == p.company
  4. def is Object (No Type Inference) class City { String

    name } class Person { String name } def thing = new City( name: "Philadelphia") assert "Philadelphia" == thing.name thing = new Person(name: "Joe") assert "Joe" == thing.name
  5. Safe Navigation: No NPE! class Dog { Person owner }

    Dog d1 = new Dog(owner: new Person(name: "Joe")) Dog d2 = new Dog(owner: null) Dog d3 = null assert "Joe" == d1?.owner?.name assert null == d2?.owner?.name assert null == d3?.owner?.name
  6. Operator Overloading class Speed { int mph Speed plus(Speed s)

    { new Speed(mph: mph + s.mph) } } def sum = new Speed(mph: 15) + new Speed(mph: 5) assert 20 == sum.mph
  7. Groovy Truth (Implicit Coercion via asBoolean) assert !"" assert "a"

    assert ![] assert [0] assert !null assert !0 assert 1 assert new Object()
  8. Elvis Operator assert "hi" == null ?: "hi" assert [1,

    2] == [] ?: [1, 2] assert "hi" == "" ?: "hi" ?: 0 // Mmmm... Groovy assert "Joe" == d3?.owner?.name ?: "Joe"
  9. Built-in Collections Support assert [] == new ArrayList() def l

    = ['a', 'b', 'c'] assert 'b' == l[1] assert [1, 2, 3] == [1] + [2, 3] assert [:] == new LinkedHashMap() def m = [a: 1, b: 2, c: 3] assert 1 == m.a assert 2 == m["b"]
  10. With Helpers! def immutableL = [1, 2].asImmutable() try { immutableL.add(3)

    assert false: "won't get here" } catch(UnsupportedOperationException e) {} assert [a: 1, b: 2].asSynchronized()
  11. Spread Operator def ls = ["foo", "world"] assert [3, 5]

    == ls*.size() String someMethod(String a, int b) { a + ": " + b*2 } def args = ["hi", 5] assert "hi: 10" == someMethod(*args)
  12. as Operator (asType) int[] intArray = [1, 2, 3] as

    int[] assert false.is("" as boolean) def hs1 = new HashSet([5, 3]) def hs2 = [ "hello", "world", "foo"]*.size() as Set assert hs1 == hs2
  13. "String ${Interpolation}" def name = "joe" assert "- joe" ==

    "- $name" assert "Name: Joe" == "Name: ${name.capitalize()}" def year = 2010 def yearExp = "Year: ${->year+1}" assert "Year: 2011" == yearExp year = 2011 assert "Year: 2012" == yearExp
  14. Closures vs Anonymous Inner Classes final int foo = 5;

    new Runnable() { @Override void run() { assert 5 == foo; } }.run()
  15. Closures vs Anonymous Inner Classes final int foo = 5;

    new Runnable() { @Override void run() { assert 5 == foo; } }.run()
  16. Closures vs Anonymous Inner Classes final int foo = 5

    ({ assert 5 == foo } as Runnable).run()
  17. Closures vs Anonymous Inner Classes final int foo = 5

    ({ assert 5 == foo } as Runnable).run()
  18. Any class Can Be a Functor (call) class CallMe {

    String call(String s) { "hello $s" } } def cm = new CallMe() assert "hello world" == cm("world")
  19. Closure 101 def c1 = { "implicit $it" } assert

    "implicit param" == c1("param") assert "implicit null" == c1() def c2 = { p1, p2 -> "explicit ${p1}${p2}" } assert "explicit param!" == c2("param", "!") def c3 = { String s -> "typed $s" } assert "typed param" == c3("param")
  20. Methods as Closures class FooClass { String state String appendState(boolean

    b) { "$state: $b" } } def fc = new FooClass(state: "Open") Closure c = fc.&appendState assert "Open: true" == c(true)
  21. Closure With Custom Delegate class DelClass { String prop }

    def d = new DelClass(prop: "hi") def closureHi = { assert prop == "hi" } closureHi.delegate = d closureHi.resolveStrategy = Closure.DELEGATE_ONLY closureHi()
  22. switch Minus the Suck (isCase) def someStuff = 5 switch(someStuff)

    { case 0: assert false case Float: assert false case [0..4]: assert false case [0, 2, 4]: assert false case { it % 2 == 0 }: assert false case Integer: assert true; break; case 5: assert false default: assert false }
  23. findAll (AKA filter) def numbers = [1, 2, 3, 4]

    assert [2, 4] == numbers.findAll { it % 2 == 0 }
  24. inject (AKA reduce/foldLeft) def numSum = [1, 2, 3, 4]

    assert 10 == numSum.inject(0) { acc, val -> acc + val }
  25. every def numbers2 = [-1, 0, 1] assert !numbers2.every {

    it >= 0 } assert numbers2.every { it >= -1 }
  26. any def numbers3 = [-1, 0, 1] assert !numbers3.any {

    it == 2 } assert numbers3.any { it == 0 }
  27. groupBy def words = ["joe", "pie", "world"] assert [ (3):

    ["joe", "pie"], (5): ["world"] ] == words.groupBy { it.size() }
  28. curry (partial function application) def addThree = { p1, p2,

    p3 -> p1 + p2 + p3 } // addOne fixes p1 and p2 to 1 and 2 def addOne = addThree.curry(1, 2) assert 6 == addOne(3) assert 7 == addOne(4)
  29. Combination Play assert 6 == [-1, 0, 1, 2, 3].collect

    { it + 1 }.findAll { it % 2 == 0 }.inject(0) { acc, val -> acc + val }
  30. Write Your Own! String doMath(int a, int b, def perform)

    { "perform($a,$b)=${perform(a, b)}" } assert "perform(4,3)=12" == doMath(4, 3) { a, b -> a * b } assert "perform(4,3)=7" == doMath(4, 3) { a, b -> a + b }
  31. @Delegate class SuperList { @Delegate List list = [] @Override

    boolean push(def o) { list.push(o) list.push(o) } } assert [List, Iterable, Collection, GroovyObject] == SuperList.interfaces def sl = new SuperList() sl.push(2) assert [2, 2] == sl sl.remove(0) assert [2] == sl
  32. @Immutable @Immutable class ImmutableCls { int a, b } def

    ic1 = new ImmutableCls(a: 1, b: 2) def ic2 = new ImmutableCls(1, 2) assert ic1 == ic2 assert "ImmutableCls(a:1, b:2)" == ic1.toString() try { ic1.a = 2 assert false : "Should never get here" } catch(ReadOnlyPropertyException ignore) {}
  33. @Lazy class LazyCls { int refVar = 1 @Lazy int

    p1 = { refVar }() @Lazy String p2 = "hi" } def lc = new LazyCls() lc.refVar = 2 assert lc.p1 == 2 assert lc.p2 == "hi" lc.refVar = 3 assert lc.p1 == 2