Last active
May 13, 2021 04:16
-
-
Save channyeintun/f3afc73f656afcc13a29e53387a1c695 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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