Home > Back-end >  When it comes to encapsulation in Kotlin, can most variables be public unlike Java since it has gett
When it comes to encapsulation in Kotlin, can most variables be public unlike Java since it has gett

Time:04-25

I'm sure the obvious exception is if you want a variable that is used only in the scope it's declared, but other than that, can most variables be public with a private set if you want it read-only, or private get if for some reason you want it write-only? Or are there other reasons I'm not aware of?

This might be considered an obvious answer, maybe not, but this is more just confirming my knowledge as someone who is experienced in Java and is used to having to declare all instance variables as private and with getter/setter methods.

CodePudding user response:

The same basic visibility decisions apply that you would use with the equivalent getters and setters in Java. You don’t usually create getters for every field in a class—only the ones that are necessary for using it from the outside.

Sometimes encapsulation just means not exposing more than you need to. A class that publicly exposes many getters that have no usefulness outside the class is simply harder to use. Auto-complete in the IDE is going to suggest a bunch of stuff you don’t need, and it will take longer for anyone to look at your class’s public members and understand how to use it.

Note, Kotlin does not allow you to define a var with a setter that has higher visibility than the getter.

One thing related to your question…you don’t need to defensively make properties private if you’re worried their setters might become more complicated in the future. For example, in Java, you often must resist the simplicity of exposing a public field because it prevents the possibility of evolving how the field is used or adding side effects from setting it without breaking external code, so you usually use private fields with public setters even for trivial fields. In Kotlin, you are never exposing a field publicly. Your properties can be simple ones with no custom getter or setter, but you still have the flexibility in the future to change them to use custom getters or setters and private backing properties, etc. without modifying the public face of the class.

Here's how I think it would map out from Java to Kotlin

Java Kotlin
private field, no getter or setter private val or private var
private field, public getter, no setter public val or public var with private set
private field, public getter and public setter public var
private field, no getter, public setter private var with public fun set...()
  • Related