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
- Business Analyst: How to write accurate software requirements
- Business Analyst: A simple secret to running a great meeting
- One thing a business analyst should ask about any requirement
- Business Analysts and Use Case quality: Questions to ask yourself when writing a Use Case
- The three things a Business Analyst should think about during meetings
- Testing web applications Selenium with Scala 3 and ScalaTest
- Scala Cookbook 2021: A best-selling new release in OOP and FP
- Salar Rahmanian's newsletter (and Functional Programming, Simplified)
- Our “Back To Now” app: Now available on iOS and Android
- An Android location “Fused Location Provider API” example