mirror of
https://codeberg.org/PGPainless/sop-java.git
synced 2024-12-22 12:57:57 +01:00
Kotlin conversion: Optional
This commit is contained in:
parent
ef4b01c6bd
commit
0cb5c74a11
2 changed files with 26 additions and 50 deletions
|
@ -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;
|
||||
}
|
||||
}
|
26
sop-java/src/main/kotlin/sop/util/Optional.kt
Normal file
26
sop-java/src/main/kotlin/sop/util/Optional.kt
Normal 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?)
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue