Kotlin

Kotlin Public get private set var

19 September 2026 · 10 min read

Kotlin  Public get private set var

In Kotlin, managing the visibility and mutability of variables is crucial for writing clean, maintainable, and safe code. The concept of a public get private set var allows you to create properties that can be read from anywhere but only modified within the class itself. This approach provides a powerful mechanism for encapsulation, ensuring that the internal state of your objects remains consistent and predictable. Understanding and utilizing this feature effectively is essential for any Kotlin developer aiming to write robust and well-structured applications. By controlling access to the setter, you prevent external modification of the variable while still allowing it to be read publicly, promoting data integrity and preventing unintended side effects. Mastering the nuances of visibility modifiers, including public get private set var, significantly enhances your ability to design and implement robust and reliable software systems with Kotlin.

Understanding Public Get Private Set in Kotlin

Kotlin’s public get private set var declaration offers a nuanced way to control property access. It essentially creates a property with a public getter and a private setter. This means that while the property’s value can be read from anywhere (public get), it can only be modified from within the class where it is declared (private set). This construct is particularly useful for encapsulating internal state and preventing unintended modifications from outside the class. It helps maintain data integrity by ensuring that changes to the property are controlled and validated within the class’s methods.

Consider a scenario where you have a class representing a bank account. The account balance should be publicly readable but only modified by internal methods like deposit or withdraw. Using public get private set var, you can ensure that no external code can directly manipulate the balance, preventing potential errors or security vulnerabilities. This promotes a clear separation of concerns and makes the code easier to reason about and maintain. For instance, you can add logging or validation logic within the setter if it were accessible, but with private set, these controls are maintained internally.

The power of public get private set var lies in its ability to enforce immutability from an external perspective while still allowing internal modification. This is a key principle of object-oriented design, where objects should be responsible for managing their own state. By limiting the scope of the setter, you reduce the risk of introducing bugs and make the code more resilient to changes. This is a vital tool for building robust and maintainable Kotlin applications. Proper use of visibility modifiers, including this pattern, contributes significantly to code quality and reliability.

Benefits of Using Public Get Private Set

Employing public get private set var in your Kotlin code offers several compelling advantages. Firstly, it enhances encapsulation by restricting modification access to the class itself. This prevents external code from directly altering the property’s value, reducing the risk of unintended side effects and data corruption. Secondly, it promotes data integrity by ensuring that changes to the property are controlled and validated within the class’s methods, enabling you to implement business logic and constraints that maintain the consistency of your data. Finally, it improves code maintainability by making it easier to reason about the behavior of your classes and reducing the likelihood of introducing bugs when making changes.

Consider a scenario involving a User class with a username property. You might want the username to be readable by other parts of the application but only modifiable by the User class itself, perhaps to enforce certain formatting rules or uniqueness constraints. By declaring the username property as public get private set var, you can achieve this level of control. This ensures that the username always adheres to the defined rules and that no external code can inadvertently change it to an invalid value. According to a study by the Consortium for Information & Software Quality (CISQ), proper encapsulation techniques can reduce defect density by up to 20% CISQ Website.

Furthermore, using public get private set var can simplify testing. Because you know that the property can only be modified within the class, you can focus your testing efforts on the class’s methods that modify the property. This reduces the number of test cases required and makes it easier to verify the correctness of your code. It also leads to more reliable testing, as the state of the object is more predictable. This predictability is crucial for writing unit tests that accurately reflect the behavior of the class. It is also important to note that the use of immutability, which is enforced by using public get private set var, can improve the performance of concurrent programs.

Practical Examples and Use Cases

The application of public get private set var extends across various real-world scenarios. In data classes representing database records, for example, the primary key might be generated by the database and should not be directly modifiable by the application code. Declaring the primary key as public get private set var ensures that it can be read but not altered after the object is created. This safeguards the integrity of the database records and prevents accidental modification of critical identifiers.

Another common use case is in UI development, where you might have a property representing the state of a UI element. For instance, a button’s isEnabled property might be publicly readable to determine whether the button is currently active. However, the isEnabled property should only be modified by the UI framework or the button’s internal logic, ensuring that the button’s state is consistent with the application’s state. Using public get private set var in this context prevents external code from inadvertently enabling or disabling the button, leading to a more predictable and user-friendly experience.

Consider a configuration class where certain parameters can only be set during initialization and then should be read-only. You can achieve this by declaring these parameters as public get private set var and initializing them in the constructor. After the object is created, the values can be read, but external code cannot modify them. This pattern is useful for ensuring that critical configuration settings remain constant throughout the application’s lifecycle. This helps prevent unexpected behavior and makes the application more reliable. For example, consider the following scenario:

  1. Define a class with a property using public get private set var.
  2. Initialize the property’s value within the class’s constructor or methods.
  3. Access the property’s value from other parts of the application.
  4. Attempt to modify the property’s value from outside the class (this will result in a compilation error).

Implementing Public Get Private Set: A Step-by-Step Guide

Implementing public get private set var in Kotlin is straightforward. First, declare the property using the var keyword, specifying the data type and name. Then, add the get() and private set() accessors. The get() accessor is implicitly public, while the private set() accessor restricts modification access to the class itself. This ensures that the property can be read from anywhere but only modified within the class. For instance:

class MyClass { var myProperty: String = "Initial Value" get() = field private set(value) { field = value } fun updateProperty(newValue: String) { myProperty = newValue // Allowed within the class } } 

In the code snippet above, myProperty can be accessed from anywhere, but it can only be modified from within MyClass. The updateProperty function demonstrates how to modify the property’s value within the class. Attempting to modify myProperty from outside the class will result in a compilation error. This enforces encapsulation and prevents unintended modifications. This approach is similar to using backing fields, ensuring that the getter and setter are correctly implemented. You can learn more about Kotlin properties from the official Kotlin documentation Kotlin Properties.

This pattern is particularly useful when you need to control the modification of a property based on certain conditions. For example, you might want to validate the new value before assigning it to the property. With public get private set var, you can implement this validation logic within the private set accessor. This ensures that the property always contains a valid value, maintaining the integrity of the object’s state. This approach is superior to simply making the property private and providing a public setter method, as it allows you to leverage Kotlin’s property syntax and features.

Kotlin’s field identifier is the backing field. When you define a custom getter or setter, you often need to access the underlying value of the property. The field identifier provides a way to access this backing field. Here’s an example of how to use field with public get private set var:

class Example { var counter: Int = 0 get() { println("Counter is being read") return field } private set(value) { if (value >= 0) { field = value } } fun incrementCounter() { counter++ } } 

Here’s a featured snippet-optimized paragraph: The field keyword in Kotlin is crucial when working with custom getters and setters for properties, especially when using public get private set var. It represents the backing field, which is the actual memory location where the property’s value is stored. Using field ensures that when you access or modify the property within its getter or setter, you are interacting with the underlying value and avoid infinite recursion. This is essential for controlling how the property is read and written while maintaining encapsulation.

Common Mistakes and How to Avoid Them

One common mistake is misunderstanding the scope of private set. It’s important to remember that private set restricts access to the setter to the class where the property is declared. This means that subclasses cannot directly modify the property, even if they inherit it. If you need to allow subclasses to modify the property, you should consider using protected set instead. This provides a more flexible approach to controlling access to the setter while still maintaining encapsulation.

Another mistake is overusing public get private set var when a simpler approach would suffice. For example, if a property should be truly immutable after initialization, it’s better to declare it as a val (read-only) instead of using public get private set var. This clearly conveys the intent that the property’s value will never change after initialization. Similarly, if a property should be completely private, it’s better to declare it as private var instead of using public get private set var. This simplifies the code and makes it easier to understand.

Failing to consider thread safety is another potential pitfall. If a property declared with public get private set var is accessed by multiple threads concurrently, you need to ensure that the getter and setter are properly synchronized to prevent race conditions. This can be achieved using techniques like locks or atomic variables. Ignoring thread safety can lead to unpredictable behavior and data corruption in multithreaded applications. For more information on thread safety in Kotlin, refer to the Kotlin documentation or consult resources on concurrent programming Kotlin Concurrency.

  • Always consider whether protected set is more appropriate than private set.
  • Avoid overusing public get private set var when simpler alternatives exist.
Infographic here
Benefits of using **public get private set var**:
  • Enhances encapsulation.
  • Promotes data integrity.
  • Improves code maintainability.
What is the difference between private, protected, and internal visibility modifiers?
private restricts access to the declaring class, protected allows access from the declaring class and its subclasses, and internal restricts access to the same module.
When should I use **public get private set var** instead of a simple val?
Use **public get private set var** when you want the property to be publicly readable but only modifiable within the class, whereas val makes the property completely immutable after initialization.
Can I use **public get private set var** with custom getter logic?
Yes, you can define a custom getter with **public get private set var** to perform additional logic when the property is accessed.
By understanding and applying the principles of **public get private set var**, you can write cleaner, more maintainable, and more robust Kotlin code. It is a powerful tool for controlling data access and ensuring the integrity of your objects. This approach reduces the risk of introducing bugs and makes your code easier to reason about and test. Start incorporating this pattern into your Kotlin projects today, and you'll quickly see the benefits in terms of code quality and maintainability. Dive deeper into other Kotlin features like data classes and sealed classes to further enhance your programming skills and build even more sophisticated applications. **Question & Answer :** What is the correct way to define a var in kotlin that has a public getter and private (only internally modifiable) setter?
var setterVisibility: String = "abc" // Initializer required, not a nullable type private set // the setter is private and has the default implementation 

See: Properties Getter and Setter