Skip to content

Instantly share code, notes, and snippets.

@jamiesanson
Last active July 24, 2018 03:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamiesanson/6a3134d7d464b22c56b624848e225a53 to your computer and use it in GitHub Desktop.
Save jamiesanson/6a3134d7d464b22c56b624848e225a53 to your computer and use it in GitHub Desktop.
Resolving resources in a weird, Kotlin-y way
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