package example

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

课程:

package example

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

Error:

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

但是official documentation描述了如果我们不指定任何可见性修改器,默认情况下使用public.

Why is above error coming?

推荐答案

What you are trying to do is accessing a value of a class that has no instance. Here are three solutions:

package example

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

This way you do not need to instantiate anything because of the way objects work in Kotlin.

You could also just instantiate your class like this:

package example

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

In this solution you also have an object of Apple, but Apple is still declared as a class.

第三个选项是一个伴生对象,其行为类似于Java中的静态变量.

package example

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

Kotlin相关问答推荐

Kotlin编译器如何决定是否可以在任何给定点调用Suspend方法?

Kotlin:类型不匹配:推断的类型已运行,但应等待

如何修改muableStateMapOf的值?

数据源配置

为什么 <= 可以应用于 Int 和 Long,而 == 不能?

在 kotlin 中使具体化字段可选

可组合项在返回后返回时组合导航句柄

返回 kotlin 中的标签和 lambda 表达式

Eclipse:无法安装 Kotlin 插件

为什么 Kotlin 的 null 安全性不能与局部变量初始化器一起正常工作?

如何从kotlin中的ArrayList中删除所有元素

Kotlin 1.2.21 + SimpleXml 2.3.0 - consume List error (must mark set get method)

Kotlin 中的数据类

无法在 kotlin android 中以编程方式禁用 EditText

Foo::class.java 和 Foo::javaClass 有什么区别?

变量后的Android问号

Kotlin suspend fun

当被Spring代理类访问时,Kotlin实例变量为null

使用导航组件在不同的图形之间导航

Android Jetpack Compose 中的文本渐变