Last active
July 24, 2018 03:06
-
-
Save jamiesanson/6a3134d7d464b22c56b624848e225a53 to your computer and use it in GitHub Desktop.
Resolving resources in a weird, Kotlin-y way
This file contains 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
var resources: Resources? = null | |
val something by R.string.abc_capital_off<String>() | |
private inline operator fun <reified T> Int.invoke(): ReadOnlyProperty<Any, T> { | |
return when { | |
String is T -> StringResolvingDelegate(this) | |
else -> throw IllegalArgumentException("Unexpected resource type") | |
} as ReadOnlyProperty<Any, T> | |
} | |
inner class StringResolvingDelegate(private val id: Int): ReadOnlyProperty<Any, String> { | |
private var value: String? = null | |
override fun getValue(thisRef: Any, property: KProperty<*>): String { | |
if (value == null) { | |
value = resources?.getString(id) ?: throw IllegalStateException("Resources are null") | |
} | |
return value!! | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment