Alex
Alex

Reputation: 159

How to define the map as a constant object, not in a method which will be created again and again

This is my method which used to populate a map, and there's other data will be added in the future.

object ConfigurationService {

    fun populateCache(client: RedissonClient): RMap<String, String> {
        val map = client.getMap("map")

        map["k1"] = "v1"
        map["k2"] = "v2"
        ....

        return map
    }
}

The problem is, each time when I calling this method in my main function, it will re-create the same map content again and again, is there a way to define it as a constant map object, not in a method.

This is what I did, is that correct?

class ConfigurationService(client: RedissonClient) {
        val map = client.getMap("map")

    fun populateCache(): RMap<String, String> {

        map["k1"] = "v1"
        map["k2"] = "v2"
        ....

        return map
    }
}

Upvotes: 1

Views: 2134

Answers (1)

Joffrey
Joffrey

Reputation: 37710

One option is to extract the constant part as a property on your object:

object ConfigurationService {

    private val fixedMapContent = mapOf(
        "k1" to "v1",
        "k2" to "v2",
    )

    fun populateCache(client: RedissonClient): RMap<String, String> {
        val map = client.getMap("map")
        map.putAll(fixedMapContent)
        return map
    }
}

But I don't think that's what you're looking for.

If the client to use is always the same, another option is to inject that client into ConfigurationService (which will not be an object anymore, you'll need to inject it as well):

class ConfigurationService(private val client: RedissonClient) {

    val cache by lazy {
        val map = client.getMap("map")

        map["k1"] = "v1"
        map["k2"] = "v2"
        ....

        map
    }
}

If you want to control when the cache is initially populated (instead of lazily on first access), you can also do this:

class ConfigurationService(client: RedissonClient) {
    
    val cache = client.getMap("map")

    fun populateCache() {
        cache["k1"] = "v1"
        cache["k2"] = "v2"
        ....
    }
}

Upvotes: 2

Related Questions