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.