Kotlin conversion: Optional

This commit is contained in:
Paul Schaub 2023-10-31 12:48:23 +01:00
parent ef4b01c6bd
commit 0cb5c74a11
Signed by: vanitasvitae
GPG key ID: 62BEE9264BF17311
2 changed files with 26 additions and 50 deletions

View file

@ -1,50 +0,0 @@
// SPDX-FileCopyrightText: 2021 Paul Schaub <vanitasvitae@fsfe.org>
//
// SPDX-License-Identifier: Apache-2.0
package sop.util;
/**
* Backport of java.util.Optional for older Android versions.
*
* @param <T> item type
*/
public class Optional<T> {
private final T item;
public Optional() {
this(null);
}
public Optional(T item) {
this.item = item;
}
public static <T> Optional<T> of(T item) {
if (item == null) {
throw new NullPointerException("Item cannot be null.");
}
return new Optional<>(item);
}
public static <T> Optional<T> ofNullable(T item) {
return new Optional<>(item);
}
public static <T> Optional<T> ofEmpty() {
return new Optional<>(null);
}
public T get() {
return item;
}
public boolean isPresent() {
return item != null;
}
public boolean isEmpty() {
return item == null;
}
}

View file

@ -0,0 +1,26 @@
// SPDX-FileCopyrightText: 2023 Paul Schaub <vanitasvitae@fsfe.org>
//
// SPDX-License-Identifier: Apache-2.0
package sop.util
/**
* Backport of java.util.Optional for older Android versions.
*
* @param <T> item type
*/
data class Optional<T>(val item: T? = null) {
val isPresent: Boolean = item != null
val isEmpty: Boolean = item == null
fun get() = item
companion object {
@JvmStatic fun <T> of(item: T) = Optional(item!!)
@JvmStatic fun <T> ofNullable(item: T?) = Optional(item)
@JvmStatic fun <T> ofEmpty() = Optional(null as T?)
}
}