简体   繁体   English

Kotlin 方法接受内联类作为参数 - 如何从 Java 访问?

[英]Kotlin methods accepting inline classes as parameters - how access from Java?

Let's say I have:假设我有:

inline class Email(value: String)

and

fun something(email: Email)

now if I want to call something() from Java I can't.现在如果我想从 Java 调用something()我不能。 Because any method that is accepting an inline class as a parameter is "mangled" (more about this here: https://kotlinlang.org/docs/reference/inline-classes.html#mangling ) As far as I understood mangling renames the method name to include a "-" that's an invalid character in Java, so the method is practically invisible from Java perspective.因为接受内联 class 作为参数的任何方法都被“损坏”(更多信息在这里: https://kotlinlang.org/docs/reference/inline-classes.html#mangling )据我所知,重命名重命名方法名称包含一个“-”,它是 Java 中的无效字符,因此从 Java 的角度来看,该方法实际上是不可见的。 That's intentional probably because of strong type safety.这可能是故意的,因为强类型安全。 But I really need to make the method callable from both Java and Kotlin. Do you know some workaround?但我确实需要使该方法可从 Java 和 Kotlin 调用。您知道一些解决方法吗?

According to the KEEP that is used to discuss and plan inline classes, this is not currently possible (writing as of 1.3.11): 根据用于讨论和规划内联类的KEEP ,目前还不可能(从1.3.11开始编写):

We'll compile function compute(UInt) to compile-<hash>(Int) , where <hash> is a mangling suffix for the signature. 我们将函数compute(UInt)编译为compile-<hash>(Int) ,其中<hash>是签名的重复后缀。 Now it will not possible to call this function from Java because - is an illegal symbol there , but from Kotlin point of view it's a usual function with the name compute. 现在无法从Java调用此函数,因为 - 在那里是非法符号 ,但从Kotlin的角度来看,这是一个名为compute的常用函数。 [Emphasis mine] [强调我的]

Keep in mind that inline classes are experimental and subject to change, so perhaps in a future release this will be possible. 请记住,内联类是实验性的并且可能会发生变化,因此在将来的版本中可能会出现这种情况。 I did try annotating this with @JvmName and that is also not supported. 我确实尝试用@JvmName注释这个,但也不支持。

Please, manually disable Kotlin names mangling with @JvmName请手动禁用 Kotlin 名称与@JvmName 的混淆

@JvmName("something")    
fun something(email: Email)

See docs for more details有关详细信息,请参阅文档

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

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