IC ice
IC ice

Reputation: 69

How to create real static property in kotlin

I hava an A.java file -> class A{ public static Integer age = 30;}

and hava a B.java file -> print(A.age)

but when I convert A.java to A.kt it does't work by object or companion keyworld.

if I use object I must change it to print(A.INSTANCE.age) and if I use companion I must change it to print(A.Companion.age) , but I can't change B.java file in some condition , So what can I do for it?

Upvotes: 3

Views: 2806

Answers (3)

ice1000
ice1000

Reputation: 6569

Use

class A {
  companion object {
    @JvmField var age = 114514
  }
}

Or simply

object A {
  @JvmField var age = 114514
}

Both codes above will create a public static int member for class A.

According to the comment, to avoid creating an object, you may make use of file-scope variables.

// A.kt
@file:JvmName("A")
package your.pkg

@JvmField var age = 114514

And you can access this public static int age via A.age in Java.

Upvotes: 9

Dominik G.
Dominik G.

Reputation: 700

You might also consider declaring it at the top-level outside of a (companion) object:

var age = 30

class A {
    ...
}

This can be accessed from Java like a static class AKt containing age. You can also add @file:JvmName("A") at the top of the file containing age to get rid of the Kt suffix and access it via A.age.

Upvotes: 1

AbdulAli
AbdulAli

Reputation: 555

Kotlin properties declared in a named object or a companion object have private visibility from java code

But they can be exposed using

  • @JvmField annotation
  • lateinit modifier
  • const modifier

Read more about kotlin static fields here

Upvotes: 4

Related Questions