Changing the receiver name of the kotlin extension function JVM name

This is a common question. Say I have an extension function written in kotlin that converts DP to PX and returns NonNull Int

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

A function in java will look something like this:

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

In my opinion, $receivermakes Java-interop feel generated and unattractive.

I know that you can use annotation @JvmNamewith some combinations, such as @file:JvmNameto change the name in java.

When I try to use @JvmNamewith the target site receiver, it says

"This annotation is not applicable to the target type usageand uses the target @receiver"

Is there a way to overcome this and change the name of the recipient, and if there is no better alternative.

+5
2

@JvmName , @JvmName . .

, : , :

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

fun Int.toPx() = toPx(this)

, , , JVM. , , @JvmName("...") () inline:

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

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

Java, @JvmSynthetic.

toPx IDE , .

+6

Java ( IDE ). Kotlin, .

, , , . Kotlin ( ), JVM. , / , .

@file:JvmName, :

@file:JvmName("Ints")

fun Int.toPx() { ... }

:

val value = 328
val px = value.toPx()

Java Kotlin:

int value = 328;
Pixel px = Ints.toPx(value);

, , IntExtensions .

, Kotlin @file:JvmName , JVM (. ). @file:JvmMultifileClass.

, Int , Java Ints.

0

Source: https://habr.com/ru/post/1690618/


All Articles