Skip to content

Instantly share code, notes, and snippets.

@channyeintun
Last active May 13, 2021 04:16
Show Gist options
  • Select an option

  • Save channyeintun/f3afc73f656afcc13a29e53387a1c695 to your computer and use it in GitHub Desktop.

Select an option

Save channyeintun/f3afc73f656afcc13a29e53387a1c695 to your computer and use it in GitHub Desktop.
// PropertyDelegation/FileDelegate.kt
package propertydelegation
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
import checkinstructions.DataFile
class FileDelegate :
ReadWriteProperty<Any?, String> {
override fun getValue(
thisRef: Any?,
property: KProperty<*>
): String {
val file =
DataFile(property.name + ".txt")
return if (file.exists())
file.readText()
else ""
}
override fun setValue(
thisRef: Any?,
property: KProperty<*>,
value: String
) {
DataFile(property.name + ".txt")
.writeText(value)
}
}
// PropertyDelegation/Configuration.kt
package propertydelegation
import checkinstructions.DataFile
import atomictest.eq
class Configuration {
var user by FileDelegate()
var id by FileDelegate()
var project by FileDelegate()
}
fun main() {
val config = Configuration()
config.user = "Luciano"
config.id = "Ramalho47"
config.project = "MyLittlePython"
DataFile("user.txt").readText() eq "Luciano"
DataFile("id.txt").readText() eq "Ramalho47"
DataFile("project.txt").readText() eq
"MyLittlePython"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment