Skip to content
DeveloperMemos

How to Use Computed Properties in Kotlin

Kotlin, Properties1 min read

Computed properties are a powerful feature of Kotlin that allow us to define custom getters and setters for properties. This allows us to abstract away complex logic into a property that can be accessed just like any other variable.

To define a computed property, we use the val or var keyword followed by the property name, an equals sign, and a code block enclosed in curly braces. Inside the code block, we can define a custom getter and/or setter for the property.

For example, let's say we have a Rectangle class with width and height properties. We could define a area property as follows:

1class Rectangle(val width: Double, val height: Double) {
2 val area: Double
3 get() = width * height
4}

In this example, the area property is defined using a custom getter that calculates and returns the product of width and height. We can access the area property just like any other variable:

1val rectangle = Rectangle(5.0, 10.0)
2println(rectangle.area) // Output: 50.0

We can also define a custom setter for a property if we need to perform some action when the property is set. For example, let's say we have a Person class with a fullName property that combines the firstName and lastName properties. We could define a custom setter for the firstName and lastName properties that updates the fullName property:

1class Person(var firstName: String, var lastName: String) {
2 var fullName: String
3 get() = "$firstName $lastName"
4 set(value) {
5 val parts = value.split(" ")
6 firstName = parts.first()
7 lastName = parts.last()
8 }
9}

In this example, the fullName property is defined using both a custom getter and setter. The getter combines the firstName and lastName properties, while the setter splits the new fullName value into first and last names and updates the corresponding properties.

We can use the @JvmName annotation to specify the name of the Java getter and/or setter methods generated by the Kotlin compiler. For example:

1class Person(var firstName: String, var lastName: String) {
2 @JvmName("getFullName")
3 fun fullName(): String = "$firstName $lastName"
4
5 @JvmName("setFullName")
6 fun fullName(value: String) {
7 val parts = value.split(" ")
8 firstName = parts.first()
9 lastName = parts.last()
10 }
11}

In this example, the @JvmName annotation is used to specify that the Java getter method should be named getFullName and the Java setter method should be named setFullName.

In conclusion, computed properties are a useful feature of Kotlin that can help simplify our code and improve performance. By defining custom getters and setters, we can abstract away complex logic into a property that can be accessed just like any other variable.