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

dev.forkhandles.data.DataProperty.kt Maven / Gradle / Ivy

There is a newer version: 2.20.0.0
Show newest version
package dev.forkhandles.data

import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
import kotlin.reflect.jvm.jvmErasure

open class DataProperty(
    private val existsFn: IN.(String) -> Boolean,
    private val getFn: IN.(String) -> Any?
) : ReadOnlyProperty {
    @Suppress("UNCHECKED_CAST")
    override fun getValue(thisRef: IN, property: KProperty<*>): OUT {
        val result = thisRef.getFn(property.name)
        return when {
            result == null -> when {
                thisRef.existsFn(property.name) -> throw NoSuchElementException("Value for field <${property.name}> is null")
                else -> throw NoSuchElementException("Field <${property.name}> is missing")
            }
            property.returnType.jvmErasure.isInstance(result) -> result as OUT

            else -> throw NoSuchElementException("Value for field <${property.name}> is not a ${property.returnType.jvmErasure} but ${result.javaClass.kotlin}")
        }
    }
}





© 2015 - 2025 Weber Informatics LLC | Privacy Policy