Classes

Kotlin Properties

Working with Properties

Kotlin properties use val and var with custom getters/setters.

Understanding Kotlin Properties

In Kotlin, properties are a fundamental part of classes and objects. They provide a clean and efficient way to define and manage the state of an object. Properties in Kotlin are similar to fields in Java, but they come with built-in support for getters and setters.

Declaring Properties with val and var

In Kotlin, you can declare properties using either val or var. The val keyword is used for read-only properties, meaning once a value is assigned, it cannot be changed. The var keyword, on the other hand, allows the property to be mutable. Here's how you can declare properties using both keywords:

Custom Getters and Setters

One of the powerful features of Kotlin properties is the ability to define custom getters and setters. This allows you to add logic whenever a property is accessed or modified. Let's explore how you can define custom getters and setters:

In this example, the area property has a custom getter that calculates the area based on the current height and width. The perimeter property has a custom setter that updates the dimensions of the rectangle whenever the perimeter is set.

Backing Fields

Kotlin properties can also use backing fields, which are useful when you need to maintain state within a custom setter or getter. Backing fields are automatically generated by Kotlin and can be accessed using the field keyword. Here's an example:

In this example, the radius property uses a custom setter to ensure the radius is always positive. The backing field is accessed with field to store the validated radius value. The circumference property uses this backing field to calculate the circumference.

Late-Initialized Properties

In some cases, you might need to initialize a property later, particularly when dealing with dependency injection or unit tests. Kotlin provides the lateinit modifier for this purpose, which can only be used with var properties and non-nullable types. Here's how it works:

In the NetworkService class, the configuration property is declared with lateinit, which allows it to be initialized after the object is created. Attempting to access a lateinit property before it is initialized will result in an exception.

Previous
Enums