2

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?

Lore
  • 1,286
  • 1
  • 22
  • 57

3 Answers3

4

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.

Community
  • 1
  • 1
Lore
  • 1,286
  • 1
  • 22
  • 57
2

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

Nigel Savage
  • 991
  • 13
  • 26
  • 1
    sure, my answer only relates to the code posted in the question, there are many possible solutions based on a given context – Nigel Savage Nov 22 '19 at 14:32
1

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"
    [...]
hio
  • 915
  • 8
  • 26