javascalautils.None Maven / Gradle / Ivy
/**
* Copyright 2015 Peter Nerg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package javascalautils;
import static javascalautils.EitherCompanion.Left;
import static javascalautils.EitherCompanion.Right;
import java.io.Serializable;
import java.util.NoSuchElementException;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
/**
* Represents an empty {@link Option}.
* The {@link None} is a replacement for null
values representing a non-existing value.
* One can consider {@link None} as a collection of size 0.
* Instances of None should not be created directly, rather use the factory methods provided on {@link Option}.
*
* - {@link Option#empty()}
* - {@link Option#None()}
*
* Since {@link None} anyways cannot represent a value it is preferable to use it as a singleton saving unnecessary instance creation.
* For examples on usage refer to the documentation for {@link Option}.
*
* @author Peter Nerg
* @since 1.0
* @param
* The type of the value represented by this instance
*/
public final class None extends EmptyContainer implements Option, Serializable {
private static final long serialVersionUID = -5169653193196761412L;
/**
* Always throws {@link NoSuchElementException} since None cannot per definition hold any value.
*
* @since 1.0
*/
@Override
public T get() {
throw new NoSuchElementException("None cannot hold values");
}
/**
* Always the value provided by the supplier.
*
* @since 1.0
*/
public T getOrElse(Supplier supplier) {
return supplier.get();
}
/**
* Always returns false
.
* I.e. the predicate is never used as {@link None} represents nothing/no value.
*
* @since 1.0
*/
public boolean exists(Predicate predicate) {
return false;
}
/**
* Always returns this
.
* I.e. the function is never used as {@link None} represents nothing/no value.
*
* @since 1.0
*/
@SuppressWarnings("unchecked")
public Option map(Function function) {
return (Option) this;
}
/**
* Always returns this
.
* I.e. the function is never used as {@link None} represents nothing/no value.
*
* @since 1.2
* @since 1.0
*/
@Override
public Option flatMap(Function> function) {
// uses the Map method as it anyways produces the same result
return map(null);
}
/**
* Always the value provided by the supplier.
*
* @return The value provided by the supplier
* @since 1.0
*/
public Option orElse(Supplier