简体   繁体   English

在 Java 中使用 Kotlin Value 类

[英]Using Kotlin Value classes in Java

We have two projects, and the kotlin one publishes a package that's imported by java.我们有两个项目,kotlin 一个发布了一个由 java 导入的包。

In kotlin, is a value class like在 kotlin 中,是一个值类,如

@JvmInline
value class CountryId(private val id: UUID) {
    override fun toString(): String = id.toString()
    companion object { fun empty(): CountryId = CountryId(EMPTY_UUID) }
}

In java, we can't see a constructor, or actually instantiate this class.在java中,我们看不到构造函数,也看不到实际实例化这个类。 I have also tried creating a factory in Kotlin to create them我也尝试过在 Kotlin 中创建一个工厂来创建它们

class IdentifierFactory 
{
    companion object {
        fun buildString(): String {
            return "hello"
        }

        fun buildCountry(): CountryId {
            return CountryId.empty()
        }
    }
}

In java, I can call IdentifierFactory.Companion.buildString() and it will work, but IdentifierFactory.Companion.buildCountry() doesn't even exist.在 java 中,我可以调用IdentifierFactory.Companion.buildString()并且它会工作,但IdentifierFactory.Companion.buildCountry()甚至不存在。

Is Java really this awful with Value classes? Java 的 Value 类真的那么糟糕吗?

ps.附: I've attempted with @JvmStatic as well, with no success我也尝试过@JvmStatic,但没有成功

It is doubtful you can use IdentifierFactory.buildString() from this code.您是否可以从此代码中使用IdentifierFactory.buildString()值得怀疑。 You would need to mark it with @JvmStatic or you would have to access it as: IdentifierFactory.Companion.buildString() .您需要使用@JvmStatic对其进行标记,否则您必须将其访问为: IdentifierFactory.Companion.buildString() buildCountry() is accessible in exactly the same way buildCountry()可以以完全相同的方式访问

Anyway, the main goal of value/inline classes is to inline them whenever possible.无论如何,值/内联类的主要目标是尽可能内联它们。 That means that in the bytecode we don't operate on CountryId , but directly on the UUID object.这意味着在字节码中我们不操作CountryId ,而是直接操作UUID对象。 buildCountry() actually returns UUID and for Java interop, in most cases you just need to use UUID . buildCountry()实际上返回UUID并且对于 Java 互操作,在大多数情况下您只需要使用UUID

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

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