-
Notifications
You must be signed in to change notification settings - Fork 22
Member Reference in Kotlin: Using (::) Operator
Devrath edited this page Feb 10, 2024
·
2 revisions
- In kotlin
::
is used asmember reference
orcallable reference
operator - It is used to invoke
members
,functions
,property
of a class without invoking them
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!")
}
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")
}
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)
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)