kotlin associated objects (java static members)

1. Concept

In front of the object declaration plus companion keywords will generate the associated object. Its role is to class where the external analog static members .

Syntax: (ObjectName can be omitted)

companion object ObjectName : [0~N个父类型] {
    //伴生对象类体
}

2. Features

  • Each class defines a companion up objects;
  • Associated target is equivalent to an object outside the class, you can directly access by members of the outer class name associated object;
  • Since kotlin canceled the static keyword, associated with the object is not to make up for lack of kotlin modified static keyword static members;
  • While the companion object is a simulation where the static members of its target, but the companion object members still are members of the associated object itself, not to the members of its outer class.

3. Define the associated objects


fun main() {
    println(OuterClass.name)//伴生对象属性
    OuterClass.companionFun()//调用伴生对象方法
    OuterClass.CompanionObjectName//通过伴生对象名称获取伴生对象本身
}

class OuterClass {
    companion object CompanionObjectName {
        val name = "伴生对象属性"
        fun companionFun() {
            println("调用伴生对象方法")
        }
    }
}

4. The name of the object is omitted companion

Companion object name can be omitted, the associated object name is omitted, if you want to get the associated object itself, can be obtained by Companion.

fun main() {
    println(OuterClass.name)//伴生对象属性
    OuterClass.companionFun()//调用伴生对象方法
    OuterClass.Companion//通过Companion获取伴生对象本身
}

class OuterClass {
    companion object {
        val name = "伴生对象属性"
        fun companionFun() {
            println("调用伴生对象方法")
        }
    }
}

5. companion object extension member

The object is associated extension member, if the object associated with the name, "through external class name of the object associated members.. " The way to expand;

If the object is not associated name, "through an external class .Companion. Members of the " way extension

fun main() {
    println(OuterClass.name)//伴生对象属性
    OuterClass.companionFun()//调用伴生对象方法

    println(OuterClass.extraParam)//为伴生对象扩展属性
    OuterClass.test()//为伴生对象扩展方法
}

class OuterClass {
    companion object {
        val name = "伴生对象属性"
        fun companionFun() {
            println("调用伴生对象方法")
        }
    }
}

/**
 * 为伴生对象扩展方法
 */
fun OuterClass.Companion.test() {
    println("为伴生对象扩展方法")
}

/**
 * 为伴生对象扩展属性
 */
val OuterClass.Companion.extraParam: String
    get() = "为伴生对象扩展属性"

Guess you like

Origin www.cnblogs.com/nicolas2019/p/10960407.html