5

Let's say we have an object such as

object MyConstants {
   const val ONE: String = "One"
}

The generated bytecode resembles

public final class MyConstants {
   @NotNull
   public static final String ONE = "One";
   public static final MyConstants INSTANCE;

   private MyConstants() {}

   static {
      MyConstants var0 = new MyConstants();
      INSTANCE = var0;
   }
}

Is there a way to avoid generating the INSTANCE field while maintaining the same code layout? That means accessing fields through class both in Kotlin and Java

MyConstants.ONE
9
  • 1
    Try to annotate it with @JvmStatic Commented Mar 14, 2020 at 19:17
  • @RadekJ Doesn't work. I've tried with multiple combinations but can't get rid of that unneeded instance, and thus unneeded object allocation. Commented Mar 14, 2020 at 19:18
  • 2
    Well, that's the implementation of object. It implies creating an object that you can use just like any other object. An object without instance is a contradiction. You can use top-level constants if you don't want an object. The MyConstants.CONSTANT smells like Java to me, as this "pattern" was an effect of the language forcing you to put everything inside classes Commented Mar 14, 2020 at 20:02
  • @gpunto even with a class and a companion object it's the same. And I want clear wrapping and accessing to the constants, that's why. Commented Mar 14, 2020 at 20:16
  • @LppEdd I guess you've already tried, but what about creating a plain Kotlin file with const val ONE = "One as its only content? Commented Mar 14, 2020 at 20:28

3 Answers 3

2
object MyConstants {
@JvmStatic
 val ONE: String = "One"
}

@JvmStatic will not use the INSTANCE

Sign up to request clarification or add additional context in comments.

Comments

0

try something like this:

class MyConstants {
    companion object {
        const val ONE: String = "One"
    }
}

class Test {

    fun test(){
       System.out.println(MyConstants.ONE) 
    }
}

1 Comment

The problem is the companion object still produces an unwanted/unnedeed instance.
0

It seems you need something like this:

@file:JvmName("Constantestest")
package com.grupomacro.macropay.models

const val A = 1
const val B = 2

From java, these are accessed just as:

int a = Constantestest.A;

And the INSTANCE reference is not available anymore.

Check the answer to this related question: Hiding Kotlin object's INSTANCE field from Java (and Kotlin)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.