Java Mapping for Optional Data Members

The mapping for optional data members in Slice classes and exceptions uses a JavaBean-style API that provides methods to get, set, and clear a member's value, and test whether a value is set. Consider the following Slice definition:

Slice
class C
{
    string name;
    optional(2) string alternateName;
    optional(5) bool active;
}

The generated Java code provides the following API:

Java
public class C ...
{
    public C();
    public C(String name);
    public C(String name, String alternateName, boolean active);

    public String name;
 
    public String getAlternateName();
    public void setAlternateName(String v);
    public boolean hasAlternateName();
    public void clearAlternateName();
    public void optionalAlternateName(java.util.Optional<String> v);
    public java.util.Optional<String> optionalAlternateName();
 
    public boolean getActive();
    public void setActive(boolean v);
    public boolean isActive();
    public boolean hasActive();
    public void clearActive();
    public void optionalActive(java.util.Optional<java.lang.Boolean> v);
    public java.util.Optional<java.lang.Boolean> optionalActive();
 
    ...
}

If a class or exception declares any required data members, the generated class includes an overloaded constructor that accepts values for just the required members; optional members remain unset unless their Slice definitions specify a default value. Another overloaded constructor accepts values for all data members.

The has method allows you to test whether a member's value has been set, and the clear method removes any existing value for a member.

Calling a get method when the member's value has not been set raises java.util.NoSuchElementException.

The optional methods provide an alternate API that uses standard Java types to encapsulate the value:

  • java.util.OptionalDouble
    Encapsulates a value of type double
  • java.util.OptionalInt
    Encapsulates a value of type int
  • java.util.OptionalLong
    Encapsulates a value of type long
  • java.util.Optional<T>
    Encapsulates all other Slice types 

See Also