javaobjectkotlinkotlin-companion

Accessing a Kotlin object nested in companion object from Java


I have a structure like this in 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"
        [...]

The problem is that I must have the possibility to access the constants' values in sub-objects from Java, but it seems not possible. How can I solve that without changing the structure?


Solution

  • JB Nizet commented:

    Works fine here using

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

    and then

    PhoneBooks.PB_ID_KEY

    It works very good for me! So I think it's useful to make it visible as an answer.