dev.marksman.collectionviews.ImmutableSet Maven / Gradle / Ivy
Show all versions of collection-views Show documentation
package dev.marksman.collectionviews;
import com.jnape.palatable.lambda.adt.Maybe;
import dev.marksman.enhancediterables.ImmutableFiniteIterable;
/**
* A {@code Set} that is guaranteed at compile-time to be safe from mutation anywhere.
* In other words, it owns the sole reference to the underlying collection.
*
* In addition to guarantees of {@link Set}, an {@code ImmutableSet} provides the following benefits:
*
* - {@link ImmutableSet#toImmutable} always returns itself.
*
*
* @param the element type
*/
public interface ImmutableSet extends Set, ImmutableFiniteIterable, Immutable {
/**
* Returns an {@code ImmutableSet} containing the same elements as this one.
*
* Since this is an {@link ImmutableSet} already, this method simply returns
* itself.
*
* @return itself
*/
@Override
default ImmutableSet toImmutable() {
return this;
}
/**
* Attempts to convert this {@code ImmutableSet} to an {@code ImmutableNonEmptySet}.
*
* If successful, returns a {@link ImmutableNonEmptySet} containing the same elements as this one, wrapped in a {@link Maybe#just}.
*
* If this {@code ImmutableSet} is empty, returns {@link Maybe#nothing}.
*
* Does not make copies of any underlying data structures.
*
* @return a {@code Maybe>}
*/
@Override
default Maybe extends ImmutableNonEmptySet> toNonEmpty() {
return ImmutableSets.maybeNonEmptyConvert(this);
}
/**
* Attempts to convert this {@code ImmutableSet} to an {@code ImmutableNonEmptySet}.
*
* If successful, returns a {@link ImmutableNonEmptySet} containing the same elements as this one.
* Use this if you are confident that this {@link ImmutableSet} is not empty.
*
* If this {@code ImmutableSet} is empty, throws an {@link IllegalArgumentException}.
*
* Does not make copies of any underlying data structures.
*
* @return an {@code ImmutableNonEmptySet}
* @throws IllegalArgumentException if this {@code ImmutableSet} is empty
*/
@Override
default ImmutableNonEmptySet toNonEmptyOrThrow() {
return ImmutableSets.nonEmptyConvertOrThrow(this);
}
/**
* Creates a {@code ImmutableNonEmptySet} with the given elements.
*
* @param first the first element
* @param more the remaining elements
* @param the element type
* @return an {@code ImmutableNonEmptySet}
*/
@SuppressWarnings("varargs")
@SafeVarargs
static ImmutableNonEmptySet of(A first, A... more) {
return Sets.nonEmptySetOf(first, more);
}
}