p-sim-ecu.doip-sim-ecu-dsl.0.14.2.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
public 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
}
}
public open class DataStorage {
private val internalDataStorage: MutableMap = mutableMapOf()
/**
* Create a persistent property by means of delegation, with an initial value
* calculated by initialValue
*/
public fun storedProperty(initialValue: () -> T): StoragePropertyDelegate =
StoragePropertyDelegate(this.internalDataStorage, initialValue)
/**
* Clear all stored properties
*/
public fun clearStoredProperties(): Unit =
internalDataStorage.clear()
}