What is the benefit of putting values like this in...
# announcements
f
What is the benefit of putting values like this into a private object? Is the only purpose that we have the
PreferencesKey.
prefix?
Copy code
private object PreferencesKeys {
        val SORT_ORDER = preferencesKey<String>("sort_order")
        val HIDE_COMPLETED = preferencesKey<Boolean>("hide_completed")
    }
a
Yea, since objects are initialized at startup you can have grouped variables. You can also put them in a companion object but since companion can't be private, you'll have to append private in front of each property.
f
thank you
I could also put them as normal `val`s into the enclosing class tho. I don't really see the point
a
Putting them on a class, makes them instance variables, which is initialized at the instantiation of it. Variables declared in object are initliazed statically, i.e. before main() runs and you can reference them from anywhere at runtime.
f
even if they are private objects?
a
Yes, objects are singleton, created at startup, exist throughout the runtime.
f
I still don't get the point in the example above. There is no reason these keys need to be initialized in advance
a
https://developer.android.com/reference/kotlin/androidx/datastore/preferences/package-summary#preferencesKey(kotlin.String) Docs suggests, that there should not be multiple keys with the same name in the runtime (and with different types will even throw exception). Initalizing them at startup and having same instance of key throughout the application lifecycle may be more consistent 🙂 If you don't want to initialize them statically, then you can use lazy delegate, which doesn't initilalize the value at startup but instead at the first access and then caches it.
f
alright, thank you very much
although I think objects are initialized lazily
companion objects are static right?
a
All objects are statically initialized
f
the docs say "Object declaration's initialization is thread-safe and done at first access."
a
Strange, The decompiled code clearly shows it is statically initialized 😕
Copy code
object TestObject {
    val a = "hello"
    fun b(): Nothing = TODO()
}
Decompiled version:
Copy code
public final class TestObject {
   @NotNull
   private static final String a;
   public static final TestObject INSTANCE;

   @NotNull
   public final String getA() {
      return a;
   }

   @NotNull
   public final Void b() {
      boolean var1 = false;
      throw (Throwable)(new NotImplementedError((String)null, 1, (DefaultConstructorMarker)null));
   }

   private TestObject() {
   }

   static {
      TestObject var0 = new TestObject();
      INSTANCE = var0;
      a = "hello";
   }
}
Even object without any property seems to show the same behavior 😕
f
thanks for checking it out
no idea
a
Let's create a thread to discuss this behavior in #CQ3GFJTU1 I think the docs are not updated...