How to Create a Static Object in Kotlin Android

In this article, we will learn about how to create a Static Object in Kotlin Android.

In the companion object, you have to place the function.

Java code is given below

class Foo {
  public static int a() { return 1; }
}

Now it turns into

class Foo {
  companion object {
     fun a() : Int = 1
  }
}

You can then use it from Kotlin code like

Foo.a();

Inside the Java code, you need to call it as

Foo.Companion.a();

If you don’t want to include the companion bit, you can either add an @jvmStatic annotation or name your companion class.

Reference Documentation of Companion objects

Next Article

1. How to Iterate Through Java MAP in Android
2. How to Use Java Ternary Conditional Operator in Kotlin

Please share this post:
Posts created 64

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: