0

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".

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
C96
  • 477
  • 8
  • 33

1 Answers1

4

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.

Eddie Lopez
  • 1,101
  • 7
  • 15
  • 1
    The `constructor` keyword is only necessary for secondary constructors. Primary constructors can be defined in front of the initial braces of the class definition, without the keyword (unless you want to use annotations on it). – Tenfour04 Aug 20 '20 at 18:42
  • Indeed. Thanks for clarifying this! – Eddie Lopez Aug 20 '20 at 20:57