0

So, im trying to develop an Android app with Kotlin as an Pen and Paper RPG companion. Right now I want to make a mob class like

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
}

In another activity I want to display this information like

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 studio is constantly telling me Cannot access 'name': It is private in 'Mob', though. I thought that's what I got the get() for?

Maybe someone with more Kotlin experience can help. Thank you in advance.

Edric
  • 24,639
  • 13
  • 81
  • 91
skranz
  • 53
  • 1
  • 7
  • Hello "skranz", welcome to StackOverflow! Firstly, from what I can see from your profile, you have not gone through StackOverflow's [tour]. I highly suggest that you should do so as you can see what StackOverflow is all about. Secondly, I suggest that you should convert your `Mob` class to Kotlin's [data class](https://kotlinlang.org/docs/reference/data-classes.html), where the compiler should automatically define getters and setters for the properties in the class. Thirdly, when you mark the properties in your class with `private`, this means that they're inaccessible outside of the class. – Edric Apr 11 '20 at 13:04
  • See https://stackoverflow.com/questions/48998907/kotlin-only-getter-pulblic-private-setter/48998939#48998939 – Neoh Apr 11 '20 at 13:33

1 Answers1

3

you can try to change your class for data class like these:

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

When you use "val" your variable will be to get, when you use "var" your variable will be to get and set.

Andres Rivas
  • 162
  • 3