Skip to content

Instantly share code, notes, and snippets.

@RazmikDev
Created November 8, 2018 22:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RazmikDev/a436180c541421e8650b1cfe1bf77bc9 to your computer and use it in GitHub Desktop.
Save RazmikDev/a436180c541421e8650b1cfe1bf77bc9 to your computer and use it in GitHub Desktop.
A concept of object model with key-value serialisation support
import kotlin.reflect.KProperty
import kotlin.reflect.full.isSubtypeOf
import kotlin.reflect.full.starProjectedType
class ValueNotFoundException : Exception()
class TypeMismatchException : Exception()
typealias JavaSerializable = java.io.Serializable
class SerializableValuesMap : LinkedHashMap<String, JavaSerializable>() {
operator fun <TSerializable> getValue(thisRef: Any?, property: KProperty<*>): TSerializable
where TSerializable : Any, TSerializable : JavaSerializable {
val value = this[property.name] ?: throw ValueNotFoundException()
if (value::class.starProjectedType.isSubtypeOf(property.returnType)) {
return value as TSerializable
}
// in case if value is not TSerializable it gonna throw exception so better we do it
throw TypeMismatchException()
}
}
interface Serializable : java.io.Serializable, Iterable<Pair<String, JavaSerializable>>
interface Deserializable {
fun set(property: String, value: JavaSerializable)
fun lock()
}
// base class for hierarchy
open class SerializableItem : Serializable, Deserializable {
override fun iterator(): Iterator<Pair<String, JavaSerializable>> {
return this.valuesStore.map { entry -> entry.key to entry.value }.iterator()
}
private var isLocked = false;
override fun lock() {
isLocked = true
}
override fun set(property: String, value: JavaSerializable) {
if (isLocked)
throw UnsupportedOperationException()
valuesStore[property] = value
}
protected val valuesStore = SerializableValuesMap()
}
open class Bean1 : SerializableItem() {
val property1: String by valuesStore
val property2: Int by valuesStore
val property3: Boolean by valuesStore
}
class Bean2 : SerializableItem() {
val otherBean: Bean1 by valuesStore
}
class Bean3 : Bean1() {
val propertyX: Array<Byte> by valuesStore
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment