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

时间:2018-01-04 18:29:43

标签: android android-studio variables kotlin access-modifiers

IAutomationComponent

类别:

package example

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

错误:

  

'APPLE_SIZE_KEY'在'example.Apple'

中拥有私人访问权限

但是official documentation描述了如果我们不指定任何可见性修饰符,则默认使用package example class Store { fun buy() { val SIZE = Apple.APPLE_SIZE_KEY } }

我的第二个问题是:

为什么会出现上述错误?

2 个答案:

答案 0 :(得分:14)

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

package example

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

这样,由于object在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"
    }
}

答案 1 :(得分: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)
}