I would like to be able to extend a class so it be...
# getting-started
e
I would like to be able to extend a class so it becomes
persistable
in a flexible way (e.g. local/remote JSON file, local/remote database. After overcoming the challenges of serializing generics, instantiating <T> etc. , I came up with this working solution:
Copy code
@Serializable
sealed class Persistable<T>(@Transient internal var persistableRepository: PersistableRepository<T>? = null) {
    abstract fun save(): T?
    abstract fun setRepository(persistableRepository: PersistableRepository<T>): T
}

@Serializable
data class SampleSettings @OptIn(ExperimentalSerializationApi::class) constructor(
    @EncodeDefault var myList: MutableList<String> = mutableListOf()
) : Persistable<SampleSettings>() {
    override fun save() = runBlocking { super.persistableRepository?.save(this@SampleSettings) }
    override fun setRepository(persistableRepository: PersistableRepository<SampleSettings>): SampleSettings{
        super.persistableRepository = persistableRepository; return this
    }
}
with
PersistableRepository
representing the flexible interface to load and store the members of the class, e.g.:
Copy code
class PersistableFileRepository<T>(private val uri: Uri, private val serializer: KSerializer<T>, private val initialSettings: T, 
  private val dispatcher: CoroutineDispatcher = <http://Dispatchers.IO|Dispatchers.IO>) : PersistableRepository<T>
What is less elegant though is the fact the subclass has to override the
save()
and
setRepostory()
function . Ideally, it would look like:
Copy code
@Serializable
data class SampleSettings @OptIn(ExperimentalSerializationApi::class) constructor(
    @EncodeDefault var myList: MutableList<String> = mutableListOf()
) : Persistable<SampleSettings>()
with all persistance code abstracted/hidden in the `Persistance`library as per the C++ implementation. Can this be done in Kotlin ?