Usage of double colon:: in kotlin

In Kotlin, ::is an operator that can be used to refer to functions, properties, or constructors. The specific usage is as follows:

  1. Reference functions: You can use ::operators to reference a function. For example, ::printlnit can be used to reference printlnfunctions.
    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")  // 与上面的输出等价
    }
    
  2. Reference properties: You can use ::operators to reference a property. For example, ::lengthit can be used to reference properties Stringof a type length.
    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
    }
    

  3. Reference constructor: You can use ::operators to reference a constructor. For example, ::Personit can be used to reference Personthe constructor of a class named.
  4. Reference to member functions or member properties: You can use ::operators to reference member functions or member properties of a class. For example, myClass::myFunctionit can be used to reference a myFunctionclass 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.

Guess you like

Origin blog.csdn.net/old_land/article/details/130204744