Groovy 2.4+ is providing support for developing Android applications in Groovy. In this presentation, we see how Groovy can help streamline the development of Android apps with the Groovy language.
Groovy code more concise and more readable ! • but just as type-safe as needed! (with @TypeChecked) ! • but just as fast as needed! (with @CompileStatic) 8
.groovy ! • Remove… • public and return keywords • some parentheses • use the property notation • getMenuInflater() becomes menuInflater • use interpolated strings • and more. 24
truth // if (s != null && s.length() > 0) {...} if (s) { ... } ! // Elvis def name = person.name ?: "unknown" ! // save navigation order?.lineItem?.item?.name
truth // if (s != null && s.length() > 0) {...} if (s) { ... } ! // Elvis def name = person.name ?: "unknown" ! // save navigation order?.lineItem?.item?.name if (person.name != null && person.name.length() > 0)
truth // if (s != null && s.length() > 0) {...} if (s) { ... } ! // Elvis def name = person.name ?: "unknown" ! // save navigation order?.lineItem?.item?.name Copied by Swift, C# and CoffeeScript!
truth // if (s != null && s.length() > 0) {...} if (s) { ... } ! // Elvis def name = person.name ?: "unknown" ! // save navigation order?.lineItem?.item?.name Anything null in the chain? Null
truth // if (s != null && s.length() > 0) {...} if (s) { ... } ! // Elvis def name = person.name ?: "unknown" ! // save navigation order?.lineItem?.item?.name Better NPEs: Cannot get property name on null object
import groovy.json.* ! def json = new JsonBuilder() json.person { name 'Guillaume' age 37 daughters 'Marion', 'Erine' address { street '1 Main St' zip 75001 city 'Paris' } }
String name • an int age 45 public final class Person { private final String name; private final int age; ! public Person(String name, int age) { this.name = name; this.age = age; } ! public String getName() { return name; } ! public int getAge() { return age; } ! public int hashCode() { return age + 31 * name.hashCode(); } ! public boolean equals(Object other) { if (other == null) { return false; } if (this == other) { return true; } if (Person.class != other.getClass()) { return false; } Person otherPerson = (Person)other; if (!name.equals(otherPerson.getName()) { return false; } if (age != otherPerson.getAge()) { return false; } return true; } ! public String toString() { return "Person(" + name + ", " + age + ")"; } }
to Java 8 interface default methods • Elegant way to compose behavior – multiple inheritance without the « diamond » problem • Traits can also be stateful – traits can have properties like normal classes • Compatible with static typing and static compilation – class methods from traits also visible from Java classes • Also possible to implement traits at runtime 48