I was trying to make a generic poor-man's data persistence function that would take a MutableSet of data class and serialize it to disk. I'd like something easy for prototyping, and am OK calling "save()" on the set every so often so that if my process gets killed, I can later resume with a "load()" of the saved entries.
But I don't quite get the differences between '*', 'in', 'out', and 'Nothing' even after rereading the Generics page. This SEEMS to work without throwing errors, but I don't get why with them both being "out", I thought one would have to be "in"... or more likely I'm understanding Kotlin Generics completely wrong. Is there a correct way of doing this?
/** Save/load any MutableSet<Serializable> */
fun MutableSet<out Serializable>.save(fileName:String="persist_${javaClass.simpleName}.ser") {
val tmpFile = File.createTempFile(fileName, ".tmp")
ObjectOutputStream(GZIPOutputStream(FileOutputStream(tmpFile))).use {
println("Persisting collection with ${this.size} entries.")
it.writeObject(this)
}
Files.move(Paths.get(tmpFile), Paths.get(fileName), StandardCopyOption.REPLACE_EXISTING)
}
fun MutableSet<out Serializable>.load(fileName:String="persist_${javaClass.simpleName}.ser") {
if (File(fileName).canRead()) {
ObjectInputStream(GZIPInputStream(FileInputStream(fileName))).use {
val loaded = it.readObject() as Collection<Nothing>
println("Loading collection with ${loaded.size} entries.")
this.addAll(loaded)
}
}
}
data class MyWhatever(val sourceFile: String, val frame: Int) : Serializable
and then be able to kick off any app with
val mySet = mutableSetOf<MyWhatever>()
mySet.load()