In Kotlin, ::
is an operator that can be used to refer to functions, properties, or constructors. The specific usage is as follows:
- Reference functions: You can use
::
operators to reference a function. For example,::println
it can be used to referenceprintln
functions.fun printWithPrefix(prefix: String, message: String) { println("$prefix $message") } fun main() { val prefix = "Message:" val message = "Hello, Kotlin!" val printer = ::println // 将println函数引用赋值给printer变量 printWithPrefix(prefix, message) // 输出: Message: Hello, Kotlin! printer("$prefix $message") // 与上面的输出等价 }
- Reference properties: You can use
::
operators to reference a property. For example,::length
it can be used to reference propertiesString
of a typelength
.fun printLength(str: String) { println(str.length) } fun main() { val myString = "Hello, Kotlin!" val lengthGetter = String::length // 将String类型的length属性引用赋值给lengthGetter变量 printLength(myString) // 输出: 14 lengthGetter(myString) // 输出: 14 }
- Reference constructor: You can use
::
operators to reference a constructor. For example,::Person
it can be used to referencePerson
the constructor of a class named. - Reference to member functions or member properties: You can use
::
operators to reference member functions or member properties of a class. For example,myClass::myFunction
it can be used to reference amyFunction
class member function named.
It should be noted that ::
operators can only be used to reference existing functions, properties or constructors, and cannot be used to create new functions or properties.