6

I have defined some constants in kotlin

object Keys {
    const val SPLASH_DURATION : Long = 5000

    const val READ_TIMEOUT : Int = 200
    const val CONNECTION_TIMEOUT : Int = 200
    const val WRITE_TIMEOUT : Int = 200

    var BASE_URL = BuildConfig.SERVER_KEY
}
  • If I try to access BASE_URL in a Java class as Keys.BASE_URL. I get the error, It has private access.
  • How to resolve this. Should I need to declare constants differently in kotlin.
0

3 Answers 3

13

You can use Companion Objects

  • An object declaration inside a class can be marked with the companion keyword:

Try this way

class Keys {

    companion object {
        const val SPLASH_DURATION : Long = 5000
        const val READ_TIMEOUT : Int = 200
        const val CONNECTION_TIMEOUT : Int = 200
        const val WRITE_TIMEOUT : Int = 200

    }
}

Now you can access your const variable like this

Keys.CONNECTION_TIMEOUT;

Second Way

object Keys {
    const val SPLASH_DURATION: Long = 5000
    const val READ_TIMEOUT: Int = 200
    const val CONNECTION_TIMEOUT: Int = 200
    const val WRITE_TIMEOUT: Int = 200
}

Now you can access your const variable like this

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

Comments

4

How to solve:

Add the @JvmField

Example:

object Keys {
    const val SPLASH_DURATION : Long = 5000

    const val READ_TIMEOUT : Int = 200
    const val CONNECTION_TIMEOUT : Int = 200
    const val WRITE_TIMEOUT : Int = 200

    @JvmField
    var BASE_URL = BuildConfig.SERVER_KEY
}

Why

  1. Use @JvmField annotation on a public field in the object to tell the compiler to not generate any getter or setter
  2. Expose it as a static field in the class

See the kotlin documentation

Comments

1

enter image description here

You can just create one constants file like above screenshot.

And define your constant value like this without making any companion Objects and access it through out your projects.

your constant values:-

const val SPLASH_DURATION : Long = 5000
const val READ_TIMEOUT : Int = 200
const val CONNECTION_TIMEOUT : Int = 200
const val WRITE_TIMEOUT : Int = 200

And if you want to make companion Object than you can also do it in KOTLIN

for eg--

 class Keys {

   companion object {

       const val SPLASH_DURATION : Long = 5000
        const val READ_TIMEOUT : Int = 200
        const val CONNECTION_TIMEOUT : Int = 200
        const val WRITE_TIMEOUT : Int = 200

    }
}

and fetch it like this--

Keys.READ_TIMEOUT

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.