更改Kotlin扩展功能接收器JVM名称 [英] Changing kotlin extension function receiver JVM name

查看:107
本文介绍了更改Kotlin扩展功能接收器JVM名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个普遍的问题. 假设我有一个用kotlin编写的扩展函数,该函数将DP转换为PX并返回NonNull Int

This is a general question. Let's say I have an extension function written in kotlin which converts DP to PX and return a NonNull Int

fun Int.toPx() {  /** implementation */ }

java中的函数看起来像这样

The function in java will look something like this

public int toPx(int $receiver) {  /** implementation */ }

在我看来,$receiver使Java互操作性产生而又不那么吸引人.

In my opinion the $receiver makes the Java-interop feels generated and uninviting.

我知道您可以将@JvmName批注与@file:JvmName之类的某些组合一起使用,以更改java中的名称.

I know that you can use the @JvmName annotation with some combinations like @file:JvmName to change the name in java.

当我尝试将@JvmNamereceiver网站目标一起使用时,它说

When i'm trying to use @JvmName with the receiver site target it says

此注释不适用于目标type usage和使用网站目标@receiver"

"This annotation is not applicable to target type usage and use site target @receiver"

有没有办法克服这个问题并更改接收方的名称,如果没有,最好的替代方法是什么.

Is there a way to overcome that and change the name of the receiver and if not what is the best alternative.

推荐答案

@JvmName只能应用于函数,属性访问器和文件的顶级程序包外观.参数名称不受支持.

@JvmName can only be applied to functions, property accessors and top-level package facades for files. Parameter names are not supported.

基本上,您可以定义两个函数,一个带有一个简单的参数,另一个带有接收器:

Basically, you can define two functions, one taking a simple parameter and another one with receiver:

fun toPx(value: Int) { /* implementation */ }

fun Int.toPx() = toPx(this)

但是,可以预料的是,这将不会编译,因为这两个函数将具有相同的JVM签名.因此,要消除歧义,请将@JvmName("...")添加到扩展名,并将扩展名标记为inline:

But, expectedly enough, this won't compile because the two functions would have the same JVM signatures. So, to disambiguate them, add @JvmName("...") to the extension and (optionally) mark the extension as inline:

fun toPx(value: Int) { /* implementation */ }

@JvmName("toPxExtension") @Suppress("nothing_to_inline")
inline fun Int.toPx() = toPx(this)

要从Java隐藏扩展功能,您还可以@JvmSynthetic 注释.

此解决方案的缺点是顶级功能toPx泄漏到查看该程序包的文件的IDE完成范围中.

The downside of this solution is the top-level function toPx leaking into the IDE completion scope of the files that see the package.

这篇关于更改Kotlin扩展功能接收器JVM名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆