Skip to content

Member Reference in Kotlin: Using (::) Operator

Devrath edited this page Feb 10, 2024 · 2 revisions

About Member reference

  • In kotlin :: is used as member reference or callable reference operator
  • It is used to invoke members,functions,property of a class without invoking them

Samples

Sample:1-Referring a function without parameters

Observation

  • Note the order of print statements, Here we had referred to the displayMessage function, At this moment it will not print it
  • When we call the reference() invocation, it prints at this time

output

<--Before calling the reference-->
Hello World!
<--Before calling the reference-->

code

fun main(args: Array<String>) {
    val reference = ::displayMessage
    println("<--Before calling the reference-->")
    reference()
    println("<--Before calling the reference-->")
}

fun displayMessage(){
    println("Hello World!")
}

Sample:2-Referring a function with parameters

output

<--Before calling the reference-->
Hello World! with the name POKEMON
<--Before calling the reference-->

code

fun main(args: Array<String>) {
    val reference = ::displayMessage
    println("<--Before calling the reference-->")
    reference("POKEMON")
    println("<--Before calling the reference-->")
}


fun displayMessage(name:String){
    println("Hello World! with the name $name")
}

Sample:3-Referring constructor

output

Instance Sarah

code

fun main(args: Array<String>) {
    val refStudent = ::Student
    val instanceStudent = refStudent("Sarah")
    println("Instance ${instanceStudent.name}")
}

class Student(val name:String)

Sample:3-Referring property

output

Instance John

code

fun main(args: Array<String>) {
    val reference = Student::name
    val student = Student("John")
    println("Instance ${reference(student)}")
}

class Student(val name:String)
Clone this wiki locally