How to access fields in a Kotlin object from Java
An interesting thing I ran into today when using mixed Kotlin and Java code on an Android project is that if you want to declare constants in a Kotlin object
, you’ll either want to do this:
object Constants {
@JvmField internal val UPDATE_INTERVAL_IN_MILLISECONDS: Long = 10000
@JvmField internal val REQUEST_CHECK_SETTINGS = 100
@JvmField internal val last_known_location = "last_known_location"
}
or this:
object Constants {
internal const val UPDATE_INTERVAL_IN_MILLISECONDS: Long = 10000
internal const val REQUEST_CHECK_SETTINGS = 100
internal const val last_known_location = "last_known_location"
}
Android Studio reports that the second version that uses const
is preferred, and I can confirm that both approaches work. Regardless of which Kotlin approach you use, you can now access these fields in your Kotlin object in your Java code like this:
resolveableException.startResolutionForResult(
MainActivity.this,
Constants.REQUEST_CHECK_SETTINGS
);
if (savedInstanceState.containsKey(Constants.last_known_location)) { ...
If you don’t use one of those approaches you’ll have to reference your Kotlin fields as “get” methods from Java — and nobody wants to do that.
A few notes from the Kotlin docs before I go:
-
internal
means “visible everywhere in the same module” -
Properties annotated with
const
(in classes as well as at the top level) are turned into static fields in Java -
Annotating a property with
@JvmField
makes it a static field with the same visibility as the property itself
In summary, if you ever need to access fields in a Kotlin object from Java code, I hope this example is helpful.
Reporting from Broomfield, Colorado,
Alvin Alexander
Recent blog posts
- Free: Introduction To Functional Programming video training course
- The #1 functional programming (and computer programming) book
- The User Story Mapping Workshop process
- Alvin Alexander, Certified Scrum Product Owner (CSPO)
- Alvin Alexander is now a Certified ScrumMaster (CSM)
- Our “Back To Then” app (for iOS and Android)
- A Docker cheat sheet
- Pushing a Scala 3 JAR/Docker file to Google Cloud Run
- Reading a CSV File Into a Spark RDD (Scala Cookbook recipe)
- Reading a File Into a Spark RDD (Scala Cookbook recipe)