All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.Maybe.kt Maven / Gradle / Ivy

There is a newer version: 0.14.0
Show newest version
package io.fluidsonic.stdlib


// FIXME no inline class b/c it still causes ClassCastExceptions in Kotlin 1.4.10
@Suppress("NON_PUBLIC_PRIMARY_CONSTRUCTOR_OF_INLINE_CLASS")
public class Maybe @PublishedApi internal constructor(
	@PublishedApi internal val _value: Any?,
) {

	override fun equals(other: Any?): Boolean =
		this === other || (other is Maybe<*> && _value == other._value)


	override fun hashCode(): Int =
		_value.hashCode()


	@Suppress("NOTHING_TO_INLINE", "UNCHECKED_CAST")
	public inline fun getOrNull(): Value? =
		if (hasValue()) _value as Value
		else null


	@Suppress("NOTHING_TO_INLINE")
	public inline fun hasValue(): Boolean =
		!isNothing()


	@Suppress("NOTHING_TO_INLINE", "UNCHECKED_CAST")
	public inline fun get(): Value =
		if (hasValue()) _value as Value
		else error("Cannot get value from Maybe.nothing. Check with .hasValue() first.")


	@Suppress("NOTHING_TO_INLINE")
	public inline fun isNothing(): Boolean =
		_value === nothingValue


	@Suppress("UNCHECKED_CAST")
	public inline fun  map(mapping: (Value) -> TransformedValue): Maybe =
		if (hasValue()) Maybe(mapping(_value as Value))
		else nothing


	override fun toString(): String =
		if (_value === nothingValue) ""
		else _value.toString()


	public companion object {

		@PublishedApi
		internal val nothingValue: Any = Any()

		public val nothing: Maybe = Maybe(nothingValue)


		@Suppress("NOTHING_TO_INLINE")
		public inline fun  of(value: Value): Maybe =
			Maybe(value)


		@Suppress("NOTHING_TO_INLINE")
		public inline fun  ofNullable(value: Value?): Maybe =
			Maybe(value ?: nothingValue)
	}
}


@Suppress("UNCHECKED_CAST")
public inline fun  Maybe.getOrElse(default: () -> Value): Value =
	if (hasValue()) _value as Value
	else default()


@Suppress("UNCHECKED_CAST")
public inline fun  Maybe.mapIfNotNull(
	mapping: (Value) -> TransformedValue?,
): Maybe =
	map { it?.let(mapping) }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy