【问题标题】:Access private variable in Kotlin [duplicate]在 Kotlin 中访问私有变量 [重复]
【发布时间】:2020-07-24 04:46:20
【问题描述】:

所以,我正在尝试使用 Kotlin 作为 Pen and Paper RPG 伴侣开发一个 Android 应用程序。现在我想做一个像这样的暴徒类

class Mob(name: String, health: Int, armor: Int) {
    private val name: String
        get() = field
    private var health: Int = 0
        get() = field
        set(value) {
            field = value
        }
    private val armor: Int
        get() = field
}

在另一个活动中,我想显示此信息,例如

class MeinMonster : AppCompatActivity() {

    private lateinit var monster: Mob

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_mein_monster)

        monster = Mob(
            intent.getStringExtra("Name"),
            intent.getIntExtra("Health", 20),
            intent.getIntExtra("Armor", 0)
        )
        print()
    }
    private fun print() {
        try {
            tvName.text = monster.name
            tvHealth.text = "LeP: ${monster.health}"
            tvArmor.text = "RS: ${monster.armor}"
        } catch (ex:Exception) {
            val goBack = Intent(this, MainActivity::class.java)
            startActivity(goBack)
        }
    }
}

Android 工作室不断告诉我无法访问“名称”:它在“Mob”中是私有的。我以为这就是我得到get() 的原因?

也许有更多 Kotlin 经验的人可以提供帮助。提前谢谢你。

【问题讨论】:

  • 您好“skranz”,欢迎来到 StackOverflow!首先,从我从您的个人资料中可以看出,您还没有通过 StackOverflow 的tour。我强烈建议您这样做,因为您可以看到 StackOverflow 的全部内容。其次,我建议你应该将你的 Mob 类转换为 Kotlin 的 data class,编译器应该自动为类中的属性定义 getter 和 setter。第三,当你用private标记你的类中的属性时,这意味着它们在类之外是不可访问的。

标签: android oop kotlin access-modifiers


【解决方案1】:

您可以尝试更改您的数据类,如下所示:

data class Mob(val name: String, var health: Int, val armor: Int)

当您使用“val”时,您的变量将被获取,当您使用“var”时,您的变量将被获取和设置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-28
    • 2013-02-01
    • 2017-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多