Sling Academy
Home/Kotlin/How to Define Properties in Kotlin Classes

How to Define Properties in Kotlin Classes

Last updated: November 30, 2024

In Kotlin, properties are an essential part of class definitions. They allow you to define fields within a class effortlessly while providing the functionalities of getters and setters behind the scenes. Here's how you can define properties within Kotlin classes, with examples explained clearly:

Basic Property Declaration

Kotlin allows you to declare properties in a class with concise syntax. A property in Kotlin can be mutable using var or immutable using val. Here's a basic example:

class Person {
    var name: String = ""
    val age: Int = 0
}

In the example above, name is mutable, meaning you can change its value, while age is immutable, meaning it can only be set when an instance of the class is created and cannot be changed later.

Custom Getters and Setters

Kotlin allows you to customize the getter and setter methods for a property. Here's how you can do that:

class Employee {
    var salary: Double = 0.0
        get() = field
        set(value) {
            if (value >= 0) field = value
        }
}

In the Employee class, a custom setter is defined to ensure the salary cannot be negative. The field keyword refers to the underlying value of the property that is being handled by getter and setter methods.

Lateinit and Lazy Properties

Sometimes, you don't want to initialize a property immediately. Kotlin provides lateinit for this purpose with var properties and lazy for val properties.

class Car {
    lateinit var model: String

    val engine: String by lazy {
        // Simulate a long computation
        "V8"
    }
}

fun main() {
    val car = Car()
    car.model = "Mustang"
    println(car.model) // Prints: Mustang
    println(car.engine) // Prints: V8 after computation
}

Backing Fields and Backing Properties

In some situations, you may need a backing field to store a value you want to manage via custom getter and setter logic. This can be done using a backing property. Here is an example:

class Book {
    private var _isbn = ""

    var isbn: String
        get() = _isbn
        set(value) {
            if (value.length == 13) _isbn = value
            else throw IllegalArgumentException("Invalid ISBN")
        }
}

In the Book class, _isbn is a backing field used to enforce constraints on the public isbn property. This ensures valid ISBN numbers only have 13 digits.

Conclusion

Defining properties in Kotlin is straightforward yet powerful. By leveraging mutable and immutable properties, custom getters and setters, and understanding the use of lateinit, lazy, and backing fields, you can design classes that are both easy to understand and manage. Experiment with these examples to see how Kotlin's property system can streamline your programming tasks.

Next Article: Writing Getters and Setters for Properties in Kotlin

Previous Article: Using Private, Protected, and Public Modifiers in Kotlin

Series: Kotlin Object-Oriented Programming

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin