Class OneTimeAssignment<V>

  • Type Parameters:
    V - The type of the object which is referenced.
    All Implemented Interfaces:
    Consumer<V>, Supplier<V>, Assignment<V>, ViewableAsOptional<V>, ViewableAsOptional.Single<V>

    public final class OneTimeAssignment<V>
    extends Object
    implements Assignment<V>
    A reference which may or may not be assigned a value, with the added constraint that it can only be assigned once. If it is assigned a value more than one time it will throw an exception.

    The class is thread-safe in the sense that it is not possible for concurrent threads to assign a value to it twice, though relevant cases for concurrent use are probably limited. The motivation is rather to enable fail-fast for erroneous API-usage involving assignments, e.g. builder implementations.

    • Method Detail

      • defaultTo

        public static final <V> OneTimeAssignment<V> defaultTo​(V defaultValue)
        Create a new non-assigned instance with a default value.
        Parameters:
        defaultValue - The default value to use in case an assignment through set(Object) is never performed.
        See Also:
        defaultTo(Supplier)
      • defaultTo

        public static final <V> OneTimeAssignment<V> defaultTo​(Supplier<? extends V> defaultValue)
        Create a new non-assigned instance with a default value.
        Parameters:
        defaultValue - The supplier to acquire the default value to use in case an assignment through set(Object) is never performed.
      • newInstance

        public static final <V> OneTimeAssignment<V> newInstance()
        Create a new non-assigned instance.
      • set

        public void set​(V value)
        Assigns a value to this reference. This method can only be called once.
        Specified by:
        set in interface Assignment<V>
        Parameters:
        value - the value to set.
        Throws:
        OneTimeAssignment.AlreadyAssigned - if this reference is already assigned a value.
      • isSet

        public boolean isSet()
        Determine if this OneTimeAssignment has been set, either by using set(Object) or implicitly by a default value, triggered with a call to get().

        For sake of clarity, an invocation of this method does never implicitly assign any default value. An assignment with no default value requires an invocation of set(Object) for this method to return true.

        Returns:
        true if the assignment has a value, false if it has not been assigned yet.
      • get

        public V get()
        Specified by:
        get in interface Supplier<V>
        Returns:
        the referenced value. If the reference has not yet been set but is initialized with a default value, the reference is assigned the default value and this is returned.