Kotlin:如何从另一个班级访问字段?

问题描述 投票:6回答:2
package example

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

类:

package example

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

错误:

'APPLE_SIZE_KEY'在'example.Apple'中拥有私人访问权限

但是official documentation描述了如果我们不指定任何可见性修饰符,则默认使用public

我的第二个问题是:

为什么会出现上述错误?

android android-studio variables kotlin access-modifiers
2个回答
14
投票

您要做的是访问没有实例的类的值。以下是三种解决方案:

package example

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

这样你就不需要实例化任何东西,因为objects在Kotlin中的工作方式。

您也可以像这样实例化您的类:

package example

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

在这个解决方案中,你还有一个Apple的对象,但Apple仍然被声明为一个类。

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

package example

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

5
投票

如果您希望它是类级属性而不是实例级属性,则可以使用companion object

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

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

你现在拥有的是一个实例属性,你可以这样使用:

fun useInstanceProperty() {
    val apple = Apple()
    println(apple.APPLE_SIZE_KEY)
}
© www.soinside.com 2019 - 2024. All rights reserved.