Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: How to access field from another class?

package example

class Apple {
    val APPLE_SIZE_KEY: String = "APPLE_SIZE_KEY"
}

Class:

package example

class Store {
     fun buy() {
      val SIZE = Apple.APPLE_SIZE_KEY
    }
}

Error:

'APPLE_SIZE_KEY' has private access in 'example.Apple'

But official documentation describes that if we do not specify any visibility modifier, public is used by default.

Why is above error coming?

like image 947
Malwinder Singh Avatar asked Jan 04 '18 18:01

Malwinder Singh


1 Answers

If you want this to be a class level property instead of an instance level property, you can use a companion object:

class Apple {
    companion object {
        val APPLE_SIZE_KEY: String = "APPLE_SIZE_KEY"
    }
}

fun useAppleKey() {
    println(Apple.APPLE_SIZE_KEY)
}

What you currently have is an instance property, which you could use like this:

fun useInstanceProperty() {
    val apple = Apple()
    println(apple.APPLE_SIZE_KEY)
}
like image 164
zsmb13 Avatar answered Nov 10 '22 04:11

zsmb13