Annotation Interface Default


Designates a default value for the given field. This automatically sets the field to that default value when the value of the annotated field is empty (null or empty collection/map) during the default lifecycle phase.

The default target as decided by the members must be exactly one of:

  • field: the value of the field with the given name
  • delegate: the value of an identically named field of the given delegate field. This is especially useful in with the Owner annotation to create composite like tree structures.
  • closure: execute the closure (in the context of this) and use the result

 given:
 @DSL
 class Container {
   String name
   Element element
 }

 @DSL
 class Element {
   @Owner Container owner

   @Default(delegate = 'owner')
   String name
 }

 when: "No name is set for the inner element"
 instance = Container.Create.With {
 name "outer"
   element {}
 }

 then: "the name of the outer instance is used"
 instance.element.name == "outer"

 when:
 instance = Container.Create.With {
   name "outer"
   element {
     name "inner"
   }
 }

 then:
 instance.element.name == "inner"
 }
 

Like all lifecycle annotations, this annotation can also be placed on a method, which will be executed in the phase, or on a field of type closure, which will be executed along with annotated methods.

  • Optional Element Summary

    Optional Elements
    Modifier and Type
    Optional Element
    Description
    Class<? extends groovy.lang.Closure<Object>>
    Delegates to the given closure, if the annotated field is empty.
    Delegate to a field with the same name on the targeted field, if the annotated field is empty
    Delegates to the field with the given name, if the annotated field is empty.
  • Element Details

    • field

      String field

      Delegates to the field with the given name, if the annotated field is empty.

      @Default(field = 'other') String aValue

      leads to

      aValue ?: other
      Default:
      ""
    • code

      Class<? extends groovy.lang.Closure<Object>> code

      Delegates to the given closure, if the annotated field is empty.

      @Default(code = { name.toLowerCase() }) String aValue

      leads to

      aValue ?: name.toLowerCase()
      Default:
      com.blackbuild.klum.ast.NoClosure.class
    • delegate

      String delegate

      Delegate to a field with the same name on the targeted field, if the annotated field is empty

      @Default(delegate = 'other') String aValue

      leads to

      aValue ?: parent.aValue
      Default:
      ""