The basic syntax for a property reference in Kotlin is ::propertyName
. Here is a simple example:
// Define a class
class Person(val name: String, var age: Int)
fun main() {
// Create a property reference to the 'age' property of the Person class
val ageProperty = Person::age
println(ageProperty.name) // Output: age
}
In this example, Person::age
creates a reference to the age
property of the Person
class. The name
property of the property reference gives the name of the referenced property.
class Rectangle(var width: Int, var height: Int)
fun main() {
val widthProperty = Rectangle::width
val rect = Rectangle(10, 20)
// Get the value using the property reference
println(widthProperty.get(rect)) // Output: 10
// Set the value using the property reference
widthProperty.set(rect, 30)
println(rect.width) // Output: 30
}
class Circle(var radius: Double)
fun main() {
val circle = Circle(5.0)
val radiusProperty = circle::radius
println(radiusProperty.get()) // Output: 5.0
radiusProperty.set(7.0)
println(circle.radius) // Output: 7.0
}
Property references can be used as arguments in higher - order functions. For example, you can use them with the sortedBy
function to sort a list based on a specific property.
data class Book(val title: String, val price: Double)
fun main() {
val books = listOf(
Book("Book A", 20.0),
Book("Book B", 15.0),
Book("Book C", 25.0)
)
val sortedBooks = books.sortedBy(Book::price)
sortedBooks.forEach { println(it.title) }
// Output:
// Book B
// Book A
// Book C
}
Property references can be used for reflection purposes. You can access metadata about a property, such as its name, type, and annotations.
import kotlin.reflect.full.findAnnotation
annotation class Important
class MyClass(@Important var myProperty: String)
fun main() {
val myPropertyRef = MyClass::myProperty
val annotation = myPropertyRef.findAnnotation<Important>()
println(annotation != null) // Output: true
}
Kotlin property references are a powerful feature that provides a flexible way to refer to properties. They can be used in various scenarios, such as higher - order functions and reflection. By understanding the core concepts, typical usage scenarios, and best practices, intermediate - to - advanced software engineers can effectively use property references in their Kotlin code to make it more concise and expressive.