javascalautils.Some 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 java.io.Serializable;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Stream;
/**
* Represents an {@link Option} holding a value.
* The instance of {@link Some} is guaranteed to keep a non-null value object.
* Null values are not allowed as it implies an instance of {@link None}.
* One can consider {@link Some} as a collection of size 1.
*
* Either use the implementation directly:
* Option<String> option = new Some<>("Peter is Great!");
* or use the factory/apply method from Option:
* Option<String> option = Option.apply("Peter is Great!");
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 Some implements Option, Serializable {
private static final long serialVersionUID = -17186529545151493L;
private final T value;
/**
* Creates an instance for the provided value.
* Null objects are not allowed and will render an exception.
*
* @param value
* The value represented by this Some
*/
public Some(T value) {
this.value = Validator.requireNonNull(value, "Null values are not allowed for Some");
}
/**
* Returns true
if the predicate matches the value.
*/
@Override
public boolean exists(Predicate p) {
return p.test(value);
}
/**
* Always returns the value.
*/
@Override
public T get() {
return value;
}
/**
* Always returns the value.
*/
@Override
public T getOrElse(Supplier s) {
return value;
}
/**
* Returns an Option consisting of the result of applying the given function to the current value.
*/
@Override
public Option map(Function f) {
return Option.apply(f.apply(value));
}
/**
* Returns an Option consisting of the result of applying the given function to the current value.
*/
@Override
public Option flatMap(Function> function) {
return function.apply(value);
}
/**
* Always returns this
.
*/
@Override
public Option orElse(Supplier