Avoid generating static instance of object in Kotlin

Viewed 319

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
2 Answers
object MyConstants {
@JvmStatic
 val ONE: String = "One"
}

@JvmStatic will not use the INSTANCE

try something like this:

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

class Test {

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