Callable references in Kotlin provide a way to treat functions and properties as objects. This powerful feature enables developers to pass functions as arguments, store them in variables, or return them from other functions.
In Kotlin, you can reference functions, properties, and constructors using the ::
operator. These references can be used wherever a function type is expected, making your code more flexible and reusable.
To create a reference to a function, use the function name preceded by the ::
operator:
fun isEven(n: Int): Boolean = n % 2 == 0
val predicate = ::isEven
In this example, ::isEven
creates a reference to the isEven
function, which can be stored in a variable or passed as an argument.
Similarly, you can create references to properties:
val x = 5
val xRef = ::x
println(xRef.get()) // Outputs: 5
xRef.set(10)
println(x) // Outputs: 10
Property references allow you to access and modify properties indirectly, which can be useful in various scenarios, such as reflection or dependency injection.
Callable references are particularly useful with Kotlin Higher-Order Functions. They allow you to pass functions as arguments concisely:
val numbers = listOf(1, 2, 3, 4, 5)
val evenNumbers = numbers.filter(::isEven)
You can also create references to constructors, which is helpful for factory patterns or dependency injection:
class Person(val name: String)
val createPerson = ::Person
val john = createPerson("John")
As you become more comfortable with callable references, you may want to explore related concepts:
Mastering callable references in Kotlin opens up new possibilities for writing flexible and reusable code. By treating functions and properties as first-class citizens, you can create more dynamic and expressive programs.