android-studiokotlin

why we generally dont use private variables in kotlin? like in java c++ etc


I know that Kotlin generates getters and setters internally if we don't provide it but then the variable behaves just like a public variable in java which is considered bad in java programming, but not in Kotlin why?


Solution

  • Similarly to C#, Kotlin uses the concept of properties which means you can do something like

    var name: String = “John”
    

    Giving you a private field and public getters/setters.

    Java does not have this and the fields are exposed if not defined as private or protected.