2
votes

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?

3
Works fine here using import static com.yourcompany.yourproject.YourClass.Constants.PhoneBooks;, and then PhoneBooks.PB_ID_KEY.JB Nizet
Change in an answer if you want some rep!Lore
I don't care about rep. And I would be happy to see a more elaborate answer, from someone with more knowledge than me. But at least my comment unblocks you.JB Nizet
Anyways, thank you so much. I think that also a not-so-much elaborated answer can unblock many other people ;)Lore
It doesn't works outside application packages...Lore

3 Answers

3
votes

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.

2
votes

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

1
votes

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