ewald comhaire
07/16/2023, 8:02 PMGeneric<T>
as well as instantiating `T()`but came up with a solution that looks OK (no lint errors) but crashes the Kotlin compiler. Also, I had to take out any reflection based solution as with Kotlin 1.8.20 and 18.21, it is causing stress testing to randomly fail, but I have not managed to create a minimum reproducible example yet...
Conceptually;
@Serializable
data class PersisableSettings @OptIn(ExperimentalSerializationApi::class) constructor(
// Active Setting
@EncodeDefault var userName: String = "System",
@EncodeDefault var vRunName: String = "System Run",
) : Persistable<PersisableSettings>()
@Serializable
abstract class Persistable<T: Any> { //(@Ignore private val initialValues: T, @Ignore val persistableRepository: PersistableRepository<T>) {
@Ignore private lateinit var persistableRepository: PersistableRepository<T>
@Ignore private lateinit var settings: T
operator fun invoke(initialValues: T, persistableRepository: PersistableRepository<T>) : T {
this.persistableRepository = persistableRepository
settings = persistableRepository.load() ?: initialValues
return settings
}
fun save(): T = persistableRepository.save(settings)
}
interface PersistableRepository<T> {
fun save(settings: T): T
fun load(): T?
}
// Koin instantiation using a local file based storage
single { PersisableSettings()(PersisableSettings(), PersistableFileRepository(androidContext(), "test_settings.json", PersisableSettings.serializer())) }
// Use as
val settings = get<PersisableSettings>() // Load the settings singleton via Koin
settings.save() // Save the settings
// Example implementation class (a local JSON settings file)
class PersistableFileRepository<T>(private val context: Context, private val name: String,
private val serializer: KSerializer<T>
//private val dispatcher: CoroutineDispatcher = <http://Dispatchers.IO|Dispatchers.IO>
) : PersistableRepository<T> { ... }
I filed a defect, but more likely I have taken the wrong approach . Sample implementation code that generates the error: github. Any suggestions on how to do this the right way ? Thanks in advance, Ewald
PS. Some progress made: marking the superclass parameters are protected
rather than private
makes the compiler crash go away, even though IMHO they should be private. Even better, making `Persistable<T> non serializable avoids the compiler crash and seems to be a working solutionewald comhaire
07/17/2023, 8:36 PMrepository
field for the data class be private. Managed to work around another defect where the run-time crashed because it claimed to require registered polymorphism whereas all conditions were met for it to be automatic . Need to file another issue for this. The code is working fine now,