javakotlincachingcoding-stylecaffeine

Java to Kotlin constructor method


When I move my service's constructor method to Kotlin code, I get a "Method is never used" message. What would be the correct way to transfer the below method to a Kotlin service? I think an init block could be used instead but I'm not sure.

public CurrencyServiceImpl() {
    currenciesCache = Caffeine.newBuilder().maximumSize(100).expireAfterWrite(1, TimeUnit.DAYS).build();
}

Now for Kotlin, the below throws "Function "CurrencyServiceImpl" is never used"

fun CurrencyServiceImpl() {
    currenciesCache = Caffeine.newBuilder().maximumSize(100).expireAfterWrite(1, TimeUnit.DAYS)
            .build<String, String>()
}

So I changed it to the code below:

init {
    currenciesCache = Caffeine.newBuilder().maximumSize(100).expireAfterWrite(1, TimeUnit.DAYS)
            .build<String, String>()
}

But I am not sure if that is considered "appropriate".


Solution

  • Your init is perfectly appropriate.

    Note that the fun CurrencyServiceImpl() you defined before is not a constructor but a member function, hence why it wasn't being used. Constructors in Kotlin must be declared using the cosntructor keyword.