"@JvmNoInstance" annotation for objects?


#1

I have a suggestion.
Create an annotaion for objects that will designate, that this object will be compiled in java bytecode only with static methods without creating an INSTANCE field. It will be extremely useful for creating library classes, interopable with java. :slight_smile:

object Foo {
 @JvmStatic
 val bar = "bar"
 @JvmStatic
 val baz = "baz"
}

->

@JvmNoInstance
object Foo {
  val bar = "bar"
  val baz = "baz"
}

#2

What would happen if you used that object as, well, a standard object, like assigning it to a variable or adding it to a MutableList?


#3

Add semantic analyze time inspection to disable this case?


#4

Couldn’t you just use package level members?

@file:JvmName("Foo")
val bar = "bar"
val baz = "baz"

#5

I know about this feature, but I like object access syntax.


#6

We have considered a feature like that recently in order to allow mapping expect companion objects to actual java classes with static members. It was proposed to mark these expect companions with some annotation that will prohibit using them as object instances and then it will be possible to correlate their member methods with java class’ static methods.

But after discussing that we found that feature too complex to design right now and came to a more easy solution. So this feature was postponed, though we don’t exclude the possibility of revisiting it at some point later.

You can follow this umbrella issue https://youtrack.jetbrains.com/issue/KT-19755 or its subtasks to track the progress of it.


#7

Joshua Bloch recommends enums a static final INSTANCE variable as the only surefire way to safely implement a singleton object in Java (Effective Java 2nd Edition, Item 3). If you don’t need to extend another class, he recommends an enum:

enum MySingleton {
    INSTANCE;
}

It seems to me that if enough people care about deserialization attacks on their singleton objects, the INSTANCE variable may never go away. I mean, it doesn’t need to be named INSTANCE, but since Bloch’s example uses that and Kotlin already uses that, it’s probably the least surprising name for the field.