Member Reference in Kotlin: Using (::) Operator Example
In Kotlin, the ‘::‘ operator is known ad the “member reference” or “callable reference” operator. It’s used to reference functions, properties or constructors without actually invoking them. In this tutorial, we’ll explore how to use member reference in Kotlin.
The member reference operator in Kotlin is useful when we need to pass a function as a parameter in a program.
Function References in Kotlin using (::) Operator
‘::yourFunctionName’ refers to a function by its name without invoking it.
For example:
fun main() {
val ref = ::showMessage // reference to the function
ref() // calling the function
}
fun showMessage(){
println("Hello, BigKnol Learning! ")
}
Hello, BigKnol Learning!
Kotlin Example : A Function with Parameters
Let’s open the Kotlin Playground and write the following code:
fun main() {
val refOfAdd = ::add
println("Sum :" + refOfAdd(3,5))
}
fun add(a: Int, b: Int): Int {
return a + b
}
Constructor References in Kotlin
It can refer to a constructor of a class by using ‘::class’ or ‘::class::newInstance’ syntax.
fun main() {
val constructorReference = ::DemoClass
val instance = constructorReference("Nikky")
println(instance.name)
}
class DemoClass(val name: String)
Nikky
Property References
The operator can also refer to properties of a class without accessing their values. This is useful, for example, when passing a property as a function argument.
Example:
class Student(val name: String)
fun main()
{
val getStudentReference = Student::name // reference to the property
val student = Student("Thankappan P.T")
println(getStudentReference(student)) // accessing the property using the reference
}
Essentially, the inclusion of :: in Kotlin introduces a dynamic functionality where functions, properties, and constructors take on the role of first-class citizens within the language.
This pivotal feature grants you the ability to manipulate these elements in various ways without the need for direct invocation. With ::, you gain the capacity to pass functions, properties, and constructors as parameters to other functions, providing a flexible approach to code design.
Furthermore, this operator empowers you to store these entities in variables, offering an adaptable and powerful mechanism for programming.
The utilization of :: is not merely confined to passing functions or properties; it extends to constructors as well. This means you can treat constructors as references, enabling their usage as parameters or storing them in variables.
Such versatility elevates Kotlin’s capabilities, fostering a more functional and dynamic programming paradigm. Embracing this feature facilitates the construction of more modular, reusable, and expressive code, enhancing the overall development experience in Kotlin.
Happy Coding!