001// SPDX-FileCopyrightText: 2021 Paul Schaub <vanitasvitae@fsfe.org> 002// 003// SPDX-License-Identifier: Apache-2.0 004 005package sop.util; 006 007/** 008 * Backport of java.util.Optional for older Android versions. 009 * 010 * @param <T> item type 011 */ 012public class Optional<T> { 013 014 private final T item; 015 016 public Optional() { 017 this(null); 018 } 019 020 public Optional(T item) { 021 this.item = item; 022 } 023 024 public static <T> Optional<T> of(T item) { 025 if (item == null) { 026 throw new NullPointerException("Item cannot be null."); 027 } 028 return new Optional<>(item); 029 } 030 031 public static <T> Optional<T> ofNullable(T item) { 032 return new Optional<>(item); 033 } 034 035 public static <T> Optional<T> ofEmpty() { 036 return new Optional<>(null); 037 } 038 039 public T get() { 040 return item; 041 } 042 043 public boolean isPresent() { 044 return item != null; 045 } 046 047 public boolean isEmpty() { 048 return item == null; 049 } 050}