JAI
JAI

Reputation: 133

How to access static variable of java class in kotlin?

Eg: I have a java class First

First.java

   `class First{
      public static TAG = "test"
    }`

Second.kt

  `class Second{
     First.TAG  /*Error classifier First does not have a companion object,and thus must be initialized here*/
   }`

So help me to call the static variable TAG declared in First.java inside Second.kt kotlin class

Upvotes: 2

Views: 3533

Answers (3)

Roberto Capah
Roberto Capah

Reputation: 473

First Class

package com.your.package object First { val TAG: String= "Your TAG"; }

Second Class

class Second{ First.TAG }

Kotlin doesn’t have static members or member functions, you can use companion object

Upvotes: 0

EpicPandaForce
EpicPandaForce

Reputation: 81539

Just make a proper, static final constant.

class First {
      public static final String TAG = "test"
}

Now you can call it from Kotlin.

class Second {
   fun blah() {
       val tag = First.TAG
   }
}

Upvotes: 1

user8959091
user8959091

Reputation:

Java Class:

class First {
    public static String TAG = "test";
}

Kotlin Class:

class Second {
    val secondTag: String = First.TAG
}

and there is no problem.

Try with IntelliJ IDEA

fun main(args: Array < String > ) {
    val s = Second()
    println(s.secondTag)
}

prints test

Upvotes: 3

Related Questions