Lore
Lore

Reputation: 1928

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?

Upvotes: 2

Views: 768

Answers (3)

Lore
Lore

Reputation: 1928

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.

Upvotes: 4

Parth Pitroda
Parth Pitroda

Reputation: 997

try using interface :)

  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"
    [...]

Upvotes: 1

user1409784
user1409784

Reputation:

In the comments above JB Nizet shows how to solve the issue with a static import

However Looking at the provided code I would use an Enum

// 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());

A big advantage here is code readability PhoneBooks.PB_ID_KEY flags PB_ID_KEY as a phone book constant in a clean way

like Kotlin sealed classes the kolin compiler add some nice checks for enums (exhaustive) and they are designed to provide clean readable code for pattern matching

see @Rolands answer here Kotlin: Using enums with when

Upvotes: 2

Related Questions