简体   繁体   English

如何在Kotlin中通过接口使用@jvmoverloads

[英]how to use @jvmoverloads with interface in Kotlin

My codebase is mixed java and kotlin code. 我的代码库是Java和Kotlin混合代码。 I'd like to use @JvmOverloads on interface method with default arguments. 我想在接口方法上使用@JvmOverloads和默认参数。 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 JvmOverloads不能在接口方法上使用

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): 平台声明冲突:以下声明具有相同的JVM签名(getClientCompanyId(JLorg / joda / time / DateTime;)J):

  • @JvmOverloads public open fun getClientCompanyId(clientId: Long, date: DateTime = ...): Long @JvmOverloads公共打开乐趣getClientCompanyId(clientId:Long,date:DateTime = ...):Long
  • @JvmOverloads public open fun getClientCompanyId(clientId: Long, date: DateTime = ...): Long @JvmOverloads公共打开乐趣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 thing to do in kotlin? 在科特林有可能做的事吗? Thanks for all the answers. 感谢所有的答案。

I believe the best you can do is to define the overloads yourself. 我相信您能做的最好的就是自己定义重载。 eg: 例如:

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

Spoilers ahead: This answer is not satisfying. 剧透:这个答案并不令人满意。

I ran into a similar issue while converting a Java class and interface into kotlin. 在将Java类和接口转换为kotlin时遇到了类似的问题。 The only way that my legacy Java code accepts @JvmOverloads generated code was to change my kotlin interface into an open class and change all fun() into open fun() 我的旧Java代码接受@JvmOverloads生成的代码的唯一方法是将我的kotlin interface更改为一个open class ,并将所有fun()更改为open fun()

Works but its not what we really want. 可行,但这不是我们真正想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM