'How can I keep my TAG extension from being called every time I log something?

I just realized my TAG extension code is getting called every time I log something. It makes sense that it is called every time but I'm wondering how can I stop that from happening every time?

This is my TAG code:

val Any.TAG: String
    get() {
        return if (!javaClass.isAnonymousClass) {
            val name = javaClass.simpleName
            if (name.length <= 23 || OSUtils.nougatMR1OrHigher) name else name.substring(0, 23)// first 23 chars
        } else {
            val name = javaClass.name
            if (name.length <= 23 || OSUtils.nougatMR1OrHigher) name else name.substring(name.length - 23, name.length)// last 23 chars
        }
    }

And it gets used like Log.i(TAG,"some lod")

One simple solution would be to make a class variable in every class that holds the value but if I do that then it kind of misses the point of the extension.



Solution 1:[1]

A way to do this is simple memoization by caching the computation result, this won't stop this being treated like a function call, but will mean the computation is only performed once.

Something like :

private val bagOfTags : MutableMap<Class<Any>, String> = ConcurrentHashMap()


val Any.TAG: String
    get() {
        return bagOfTags.computeIfAbsent(javaClass) {
            if (!javaClass.isAnonymousClass) {
                val name = javaClass.simpleName
                if (name.length <= 23 || OSUtils.nougatMR1OrHigher) name else name.substring(0, 23)// first 23 chars
            } else {
                val name = javaClass.name
                if (name.length <= 23 || OSUtils.nougatMR1OrHigher) name else name.substring(name.length - 23, name.length)// last 23 chars
            }
        }
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1