What should "idiomatic" Groovy code look like? What are the good practices in terms of syntax style, typing preferences? What are the nice shortcuts to be aware of to be more productive? Guillaume Laforge will answer those questions along the way!
message = 'Hello London' private String name HelloLondon(String name) { this.name = name } String greet() { return "$message, $name speaking" } } Methods and classes are public by default
{ static String message = 'Hello London' String name HelloLondon(String name) { this.name = name } String greet() { return "$message, $name speaking" } } You created both an instance property and a static property!
{ private String message = 'Hello London' private String name HelloLondon(String name) { this.name = name } String greet() { def result = "$message, $name speaking" return result } } But it’s fine to use ‘def’ for local variables
Person { private String name private int age void setName(String name) { this.name = name } String getName() { this.name } void setAge(int age) { this.age = age } int getAge() { this.age } }
Person { String name int age } Person.builder() .name('Guillaume') .age(37) .build() Different strategies available: chained setters, external builder class, type-safe initializer
123: "number 123"; break case "abc": "string abc"; break case String: "is a string"; break case [1, 2, 3]: "in list"; break case ~/.*o+.*/: "regex match"; break case { it < 3 }: "closure criteria"; break default: "unknown" }
{ if (order.getCustomer() != null) { if (order.getCustomer().getAddress() != null) { System.out.println(order.getCustomer().getAddress()); } } } // Groovy println order?.customer?.address Also give more meaningful NPEs!