Kotlin object declaration and object expression

 This article is the tutorial notes of the official website : official website address

Why use object expressions and object declarations?

    Sometimes, we need to create an object of a class that has made slight changes to a certain class without explicitly declaring a new subclass for it. Kotlin handles this situation with object expressions  and object declarations  .

Let's take a look at how object expressions and object declarations are implemented separately

Object expression Object declaration

  /**   

   * Object expression  

     */     

  ① var obj = object { 

     

    }       

 ② var obj2 = object : Any() {     

   }     

  /**

  * Object declaration

   */

③ object      MyObject {   

   

   }   

④ object MyObject2 : Any() {

         

     }

Object expression form (corresponding to ①② above

① object {}  or ② object: super class {}; 

Object table declaration form (corresponding to the above

③ object class name {} or ④ object class name: super class { 

Summary: The object expression object can be placed on the right side of the equal sign without the name;

          The object declaration object followed by the name cannot be placed on the right side of the equal sign                                                                           

Note: When using object expressions, anonymous objects can be used as types declared only in local and private scopes. If you use an anonymous object as the return type of a public function or as the type of a public property, the actual type of the function or property will be the supertype declared by the anonymous object. If you don't declare any supertype, it will be  Any. The members added in the anonymous object will not be accessible.

class C {
    // 私有函数,所以其返回类型是匿名对象类型
    private fun foo() = object {
        val x: String = "x"
    }

    // 公有函数,所以其返回类型是 Any
    fun publicFoo() = object {
        val x: String = "x"
    }

    fun bar() {
        val x1 = foo().x        // 没问题
        val x2 = publicFoo().x  // 错误:未能解析的引用“x”
    }
}
Object expression and object declaration comparison
Object expression Object declaration
Direct object{} without class name, also called anonymous object There is a class name object class name {}
 Can be placed on the right side of the equal sign in the assignment statement Cannot be placed on the right side of the equal sign in the assignment statement , because it is not an expression
Object expressions are executed (and initialized) immediately where they are used The object declaration is lazily initialized when it is first accessed
Can inherit or implement super classes Can inherit or implement super classes

===================================================================

Companion object: The object declaration inside the class can be  marked with the  companion keyword.

class DemoClass {
    companion object MyCompanionObject {
         fun method(){}
    }
}
调用:DemoClass.method()
=====================================
伴生对象的名称可以省略
class DemoClass {
    companion object{
         
    }
}
调用: DemoClass.companion

Note: The companion object looks a lot like a static class but it is still an instance member of the real object when it runs, for example: it can implement an interface

interface Factory<T> {
    fun create(): T
}

class MyClass {
    companion object : Factory<MyClass> {
        override fun create(): MyClass = MyClass()
    }
}

val f: Factory<MyClass> = MyClass

Note: The initialization of the companion object matches the semantics of the Java static initializer when the corresponding class is loaded (parsed).

 

 

Guess you like

Origin blog.csdn.net/u011288271/article/details/107358877