@Delegate, enums and visibility

Three smaller pieces of the object model: a class that forwards work to another object, an enum that carries data, and the modifiers that decide who may call a method.

@Delegate

delegate.groovy

import groovy.lang.Delegate class Printer { void print(String text) { println "printing: ${text}" } } class Report { @Delegate Printer printer = new Printer() List<String> lines = [] } def report = new Report() report.print('the report') println report.printer.getClass().simpleName

groovy delegate.groovy

printing: the report
Printer

@Delegate writes the forwarding methods of the field's class, so a report is printable without inheriting from a printer. It is the answer when the relationship is "has a" and the parent would only be a bag of methods. The annotation moved in Groovy 5: it is groovy.lang.Delegate, where Groovy 4 had groovy.transform.Delegate.

An enum with fields

enum.groovy

enum Planet { MERCURY(3.303e+23, 2.4397e6), EARTH(5.976e+24, 6.37814e6) final double mass final double radius Planet(double mass, double radius) { this.mass = mass this.radius = radius } double surfaceGravity() { 6.67300e-11 * mass / (radius * radius) } } println Planet.values()*.name() println Planet.EARTH.surfaceGravity().round(2) println Planet.valueOf('MERCURY').mass

groovy enum.groovy

[MERCURY, EARTH]
9.8
3.303E23

An enum constant may carry data through the constructor of the enum, and every constant is a singleton of the type. values(), valueOf and name() come from the compiler, not from the body.

Visibility

visibility.groovy

import groovy.transform.PackageScope class Account { private BigDecimal balance = 0 protected String owner = 'nobody' @PackageScope int attempts = 0 void deposit(BigDecimal amount) { balance += amount } BigDecimal getBalance() { balance } } def account = new Account() account.deposit(10) println account.balance println account.owner println account.attempts

groovy visibility.groovy

10
nobody
0

A method or a field with no modifier is public in Groovy, unlike Java, where the package is the default. private is enforced at run time by the call site, and @PackageScope is the Java default written out. A property with a getter is read through the getter even when its field is private.

Related

Автор статьи: Arthur Isaev

Изображение баннера