What is the kotlin way for implementing caching logic

Hello,

Caching can be implemented in different ways. In Java (for example using guice) I can achieve quite elegant solution using annotations, reflection and proxies generated on the fly by guice.

    @Singleton
    class SomeService {
        @Cache(name="findSome", expires="30mn")
        public List<Some> find(String name) {
             return doSomeDqQuery();
        }
    }

    class SomeController {
         @Inject SomeService someService;

        public void doSome() {someService.find("foo");....}
    }

It’s declarative, clean-enough but requires some instrumentation in runtime.

Is there a Kotlin way of working more or less transparently with cache without pollution main business logic with caching details (or course it can be argued - that main business logic should be aware of caching)?

Thanks in advance,
Vadim

Did you try if the same caching annotations work as you use in Java?

I would expect them to work with same runtime instrumentation – perhaps you need to add the kotlin-allopen plugin to your project however.

I’m using Kotlin with Spring and all Spring annotations, including those for caching, work as expected (in combination with the kotlin-allopen plugin which makes classes & functions non-final post compilation, for purpose of runtime instrumentation, depending on pre-configured annotations being present).

They will definitely work. But maybe there exists another more elegant approach using kotlin features.

Well I did some Googling for you and there’s nothing built in but there’s an extension library funKTionale.

See this discussion on StackOverflow for some examples:

And here’s the github repos:

It seems however that you do not have any control over caching behaviour or even cache size so I’d say, beware for OoM when using this extensively…

There’s also no cache expiry so this is only useful for really “pure” functions, not for caching things like remote lookups or database queries on data that is relatively but not completely static.

In other words, it does something kind of similar, but it’s not quite the same, so beware of the differences.

Thanks for links. Yeah, in case of pure funktionale no TTL can be specified but I think I can consider the approach as idea.