Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sagarpatel288/f25b1f47cdeb157daa36f9e3363356fe to your computer and use it in GitHub Desktop.
Save sagarpatel288/f25b1f47cdeb157daa36f9e3363356fe to your computer and use it in GitHub Desktop.
Accessing members of a companion object of Kotlin from Java
/**
* 6/16/2020
* Unlike kotlin, we have to write {@code public} keyword in Java.
* In kotlin, classes are {@code public} by default. We don't have to write.
* Unlike kotlin, we have to write {@code final} keyword in Java to save the class from inheritance.
* In kotlin, classes are {@code final} by default. They cant be inherited unless we mark it as {@code open}.
*
* @author srdpatel
* @see <a href="https://kotlinlang.org/docs/reference/classes.html">Classes and Inheritance</a>
* @see <a href="https://kotlinlang.org/docs/reference/visibility-modifiers.html">Visibility modifiers</a>
* @since 1.0
*/
public final class CallingFromJava {
/**
* 6/17/2020
* Accessing java static like members of kotlin companion object from java.
* We can access fields marked with {@code @JvmField} and methods marked with {@code @JvmStatic}.
*
* @author srdpatel
* @see <a href="https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html">Java interop</a>
* @since 1.0
*/
private void accessMembersOfCompanion() {
// Not possible due to lack of `@JvmField` for fields and `@JvmStatic` for methods.
// String staticExample = StaticInCompanionObjectClass.staticExample;
// String jvmStaticMethodExample = StaticInCompanionObjectClass.staticMethod();
String jvmStaticExample = StaticInCompanionObjectClass.jvmStaticExample;
String jvmStaticMethodExample = StaticInCompanionObjectClass.jvmStaticMethod();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment