Hello, when writing an inline fun <reified T&gt...
# language-proposals
g
Hello, when writing an inline fun <reified T> like the following:
inline fun <reified T> logd(message: String) {
if (BuildConfig.DEBUG) {
Log.d(T::class.java.simpleName, message)
}
}
If used without a specified type, the compiler will complain:
logd("abandonAudioFocus() called") // type inference failed: Not enough information to infer parameter T in (...). Please specify explicitly.
To fix this we need to specify the type:
logd<PlayerManager>("abandonAudioFocus() called")
Wouldn’t it be convenient if the compiler would infer the type of the class this code is called in in this case? Maybe with a new inline keyword ?
g
You can convert logd to extension function for type T, if you want to have context
Copy code
inline fun <reified T> T.logd(message: String) {
   if (BuildConfig.DEBUG) {
        Log.d(T::class.java.simpleName, message)
   }
}
class PlayerManager {
    fun doSmth() {
        logd("Log!")
    }
}
But such solution pollutes autocomplete
And I don’t think that your proposal is good, because it’s too implicit, for example if you use reified type to pass class instance (useful for DSLs and some other cases) and you forgot to pass it you will get parent class instead
g
In your example I see that T is not used so it’s the same as writing this:
fun <T: Any> T.logd(message: String) {
if (BuildConfig.DEBUG) {
Log.d(this.javaClass.simpleName, message)
}
}
You are right, it would be really confusing if it was that implicit, that’s why I was thinking about another keyword that could indicate it would be implicit?
g
Yes, you right, I don’t need reified there, so even better than solution with reified
g
Yes indeed