p-sim-ecu.doip-sim-ecu-dsl.0.9.0.source-code.DataStorage.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of doip-sim-ecu-dsl Show documentation
Show all versions of doip-sim-ecu-dsl Show documentation
This is a kotlin based domain specific language (dsl), to quickly and intuitively write custom DoIP ECU simulations.
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
class StoragePropertyDelegate(
private val storage: MutableMap,
private val initialValue: () -> T) : ReadWriteProperty {
override operator fun getValue(thisRef: Nothing?, property: KProperty<*>): T {
if (!storage.containsKey(property.name)) {
storage[property.name] = initialValue.invoke()
}
@Suppress("UNCHECKED_CAST")
return storage[property.name] as T
}
override operator fun setValue(thisRef: Nothing?, property: KProperty<*>, value: T) {
storage[property.name] = value
}
}
open class DataStorage {
private val internalDataStorage: MutableMap = mutableMapOf()
/**
* Create a persistent property by means of delegation, with an initival value
* calculated by initialValue
*/
fun storedProperty(initialValue: () -> T): StoragePropertyDelegate =
StoragePropertyDelegate(this.internalDataStorage, initialValue)
/**
* Clear all stored properties
*/
fun clearStoredProperties() =
internalDataStorage.clear()
}