2

我在 Kotlin 中有这样的结构

companion object Constants {
    /**
     * Collection of fields and values relative to phone books.
     */
    object PhoneBooks {
        /**
         * Field indicating the ID of a phone book.
         * Each phone book must have an unique ID.
         */
        const val PB_ID_KEY = "PB_ID"

        /**
         * Field indicating the status of phone book.
         */
        const val PB_STATUS_KEY = "PB_Status"

        /**
         * One of the possible [PB_STATUS_KEY] values, when the phone book is in indexing state
         * (usually at startup or in update phase).
         */
        const val PB_INDEXING = "Indexing"
        [...]

问题是我必须有可能从 Java 访问子对象中的常量值,但这似乎是不可能的。我怎样才能在不改变结构的情况下解决这个问题?

4

3 回答 3

3

JB Nizet评论道:

在这里工作正常

import static com.yourcompany.yourproject.YourClass.Constants.PhoneBooks;

进而

PhoneBooks.PB_ID_KEY

它对我很有用!所以我认为让它作为答案可见是有用的。

于 2019-11-25T15:25:10.727 回答
2

在上面的评论中,JB Nizet 展示了如何使用静态导入来解决问题

但是查看提供的代码我会使用枚举

// kotlin
enum class PhoneBooks(val param:String) {
    PB_ID_KEY("PB_ID"),
    PB_STATUS_KEY("PB_Status"),
    PB_INDEXING("Indexing")

}

// java
System.out.println(PhoneBooks.PB_ID_KEY.getParam());

这里的一大优势是代码可读性 PhoneBooks.PB_ID_KEY 以干净的方式将 PB_ID_KEY 标记为电话簿常量

像 Kotlin 密封类一样,kolin 编译器为枚举添加了一些很好的检查(详尽),它们旨在为模式匹配提供干净可读的代码

请参阅@Rolands 在这里回答 Kotlin: Using enums with when

于 2019-11-22T13:48:49.193 回答
1

尝试使用界面:)

  companion object Constants {
/**
 * Collection of fields and values relative to phone books.
 */
interface PhoneBooks {
    /**
     * Field indicating the ID of a phone book.
     * Each phone book must have an unique ID.
     */
    const val PB_ID_KEY = "PB_ID"

    /**
     * Field indicating the status of phone book.
     */
    const val PB_STATUS_KEY = "PB_Status"

    /**
     * One of the possible [PB_STATUS_KEY] values, when the phone book is in indexing state
     * (usually at startup or in update phase).
     */
    const val PB_INDEXING = "Indexing"
    [...]
于 2019-12-04T14:24:10.000 回答