Getter and Setter in Kotlin

Learn via video courses
Topics Covered

Overview

Getter and setter in Kotlin are mechanisms that control the way properties (variables) are read (get) and modified (set) within a class. They can be automatically generated by the compiler or customized to include additional logic. Getters retrieve property values, and setters assign new values while allowing you to apply validation or transformations. They help maintain data integrity, encapsulation, and controlled access to class properties.

Introduction

Getter and setter in Kotlin are essential tools for managing the access and modification of class properties, also known as fields or attributes. They enable controlled interaction with these properties, maintaining encapsulation and providing a mechanism to read and update values.

Here are the major key points about getters and setters in Kotlin:

  1. Access Control:

    Getter and setter in Kotlin provide a means to control how class properties are accessed and modified. This control prevents direct manipulation of the underlying data, promoting data integrity and encapsulation.

  2. Custom Logic:

    Getter and setter in Kotlin empower developers to incorporate custom logic during property retrieval and assignment. This capability allows for validation, calculations, or additional actions to be seamlessly integrated into property interactions.

  3. Property Syntax:

    Kotlin's concise syntax simplifies the declaration of properties and their associated getters and setters. By default, properties come with implicit getters and setters, reducing boilerplate code and enhancing code readability.

  4. Backing Fields:

    Behind the scenes, Kotlin generates backing fields to store property values. Backing fields in Kotlin are auto-generated by the compiler to store property data. Getters retrieve data from these fields, and setters modify them. This abstraction shields the details of data storage from external interactions.

  • Example of a backing field in Kotlin:

    In this example, count uses a countValue backing field. The getter retrieves it, and the setter permits non-negative changes, illustrating the role of a backing field in custom access logic.

Default Getter and Setter in Kotlin

Default getter and setter in Kotlin are automatically generated for properties. Here's an example code illustrating default setters and getters:

Output

In this example, the SimpleCounter class has a property count. Default setters and getters are automatically generated for this property. The main function demonstrates how to use the default setter to assign a value and the default getter to retrieve and display the value of the count property.

Value and Field Identifiers

In Kotlin, value and field are special identifiers used in custom getter and setter for properties.

Value

Inside a custom setter, value refers to the value being assigned to the property. It allows you to apply logic before storing the value.

Explanation:

  • When you assign a new value to the age property, the custom setter is triggered.
  • The value identifier represents the new value that you're trying to assign to the age property.
  • The if statement checks if the new value is greater than or equal to 0.
  • If the condition is true, the field (the backing field for the age property) is updated with the new value.
  • If the condition is false (i.e., the new value is negative), the age property's value remains unchanged.

Field

In Kotlin, field is used in custom getter and setter to access the property's backing field, preventing recursion in setters. It's implicitly generated for properties and only needs to be declared explicitly when direct backing field access is necessary.

Explanation:

  • When you assign a new value to the count property, the custom setter is triggered.
  • The value identifier represents the new value that you're trying to assign to the count property.
  • The if statement checks if the new value is greater than or equal to 0.
  • If the condition is true, the field (backing field) is updated with the new value.
  • If the condition is false (i.e., the new value is negative), the count property's value remains unchanged.
  • When you access the count property's value, the custom getter is triggered.
  • The getter calculates and returns the value by multiplying the field (backing field) by 2.

Private Modifier

In Kotlin, the private modifier is an access modifier used to restrict the visibility of a class member (property, function, or nested class) to within the same class where it is declared. This ensures that the member can only be accessed and modified from within that class and is not accessible from outside.

Encapsulation in Kotlin is achieved through the private modifier, which limits access to class members within the class where they're declared. This shields internal details, promoting code organization, security, and maintenance.

Output:

In this example, the SecretMessage class has a private function showMessage() and a private property message. The revealSecret() function is a public method that calls the private showMessage() function. The main function demonstrates that the private property message cannot be accessed directly from outside the class.

Custom Mutators and Accessors

In Kotlin, custom mutators (setters) and accessors (getters) allow you to define specialized behavior when accessing or modifying properties. This enables you to add validation, transformations, or custom logic while maintaining encapsulation.

Custom Mutators (Setters)

Custom setters allow you to control how property values are assigned. You can add conditions, transformations, or additional actions before setting the value.

In Kotlin, you can fully override the default setter of a property by explicitly declaring a custom setter. This lets you define your own logic for property value assignment, offering complete customization options.

Explanation:

In this example, the Student class has a custom setter for the age property. The custom setter ensures that the age is within a valid range (6 to 18 years). If an invalid age is assigned, it prints a message. The main function demonstrates how the custom setter is used to validate and set the student's age.

Custom Accessors (Getters)

Custom getters let you define how property values are retrieved.They allow for dynamic calculations, output formatting, or other operations to be executed before the value is returned.

In Kotlin, you can fully override the default getter of a property by explicitly declaring a custom getter. This empowers you to control how property values are retrieved, enabling dynamic calculations, formatting, or any other needed operations.

Explanation:

In this example, the Circle class has a private property radius and a custom getter for the area property. The custom-getter calculates and returns the area of the circle based on the radius. The main function demonstrates how the custom getter is used to retrieve the circle's size.

Conclusion

  1. Getter and setter in Kotlin control how you retrieve and update data in a class. They help maintain data integrity and control access to properties.
  2. Kotlin generates default getters and setters automatically, making it easy to work with properties. These default behaviors can be used as-is or customized.
  3. value is a placeholder in setters representing the new value being assigned. field is used in custom getters and setters to access the underlying data storage.
  4. The private modifier restricts the use of properties and methods within the same class. It protects sensitive data and internal implementation details from outside interference.
  5. Custom getters allow you to add extra logic when retrieving property values. This can include calculations, transformations, or formatting to provide more meaningful or processed data to the caller.