commonMain.com.bkahlert.kommons.debug.properties.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of kommons-debug Show documentation
Show all versions of kommons-debug Show documentation
Kommons Debug is a Kotlin Multiplatform Library for print debugging.
package com.bkahlert.kommons.debug
import kotlin.reflect.KProperty
import kotlin.reflect.KProperty0
import kotlin.reflect.KProperty1
/**
* A [Map] of this object's properties with each [Map.Entry.key] representing
* a property name and [Map.Entry.value] the corresponding value.
*/
public expect val Any.properties: Map
/** Gets the value of this property or `null` otherwise. */
@Suppress("NOTHING_TO_INLINE")
public inline fun KProperty.getOrNull(receiver: Any? = null): V? = getOrElse(receiver) { null }
/** Gets the value of this property or the result of [onFailure]. */
public fun KProperty.getOrElse(receiver: Any? = null, onFailure: (Throwable) -> V): V {
@Suppress("UNCHECKED_CAST")
return when (this) {
is KProperty0<*> -> (this as KProperty0).getOrElse(onFailure)
is KProperty1<*, *> -> (this as KProperty1).getOrElse(requireNotNull(receiver) { "receiver required for this property" }, onFailure)
else -> onFailure(IllegalStateException("unsupported property type ${renderType()}"))
}
}
internal data class PropertyAccessError(private val exception: Throwable) {
override fun toString(): String = ""
}
/** Gets the value of this property or the result of [onFailure]. */
public expect fun KProperty0.getOrElse(onFailure: (Throwable) -> V): V
/** Gets the value of this property or the result of [onFailure]. */
public expect fun KProperty1.getOrElse(receiver: T, onFailure: (Throwable) -> V): V