1

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

5
  • I am using both android and kotlin inside the same project Commented Jul 18, 2018 at 9:30
  • as a side note it should be public static String TAG you are missing String Commented Jul 18, 2018 at 9:32
  • 1
    use full qualified name instead of First.TAG use <your package>.First.TAG kotlinlang.org/docs/reference/java-interop.html Commented Jul 18, 2018 at 9:32
  • 2
    Why would you do that? it's not clear what you are trying to do with First.TAG . If you want to create a member variable var someMember = First.TAG and why does TAG not have a type in your java class. I am guessing it's a String Commented Jul 18, 2018 at 9:33
  • Also in Kotlin you can use Companion object, just like static methods in Java. Commented Jul 18, 2018 at 10:38

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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
   }
}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.