How to use @JvmOverloads with overriden function with default arguments?


#1

My codebase consists of mixed java and kotlin code. I’d like to use @JvmOverloads on interface method with default arguments. Like that:

@JvmOverloads
fun getClientCompanyId(clientId: Long, date: DateTime = DateTime.now()): Long

I can’t do this unfortunately and I get the message that:

JvmOverloads cannot be used on interface methods

However if I use it on overridden function then I get

Platform declaration clash: The following declarations have the same JVM signature(getClientCompanyId(JLorg/joda/time/DateTime;)J):

  • @JvmOverloads public open fun getClientCompanyId(clientId: Long, date: DateTime = …): Long
  • @JvmOverloads public open fun getClientCompanyId(clientId: Long, date: DateTime = …): Long

and just for the record: when I try to put default value in overridden method I get the message that:

An overriding function is not allowed to specify default values on its parameters

Is it a possible to do such thing in kotlin? Thanks for all the answers.


#2

I know that this is a bit old, but I had a similar problem today, so thought the reply might come in handy.
You can specify default values for overrides, but you have to do that when you declare the function in the interface, not when you define the function in the implementing class. You can read a bit about here in the docs: https://kotlinlang.org/docs/reference/functions.html