Kotlin six objects expressions and object declarations

Expression and a target object declaration

Kotlin object-expression and create an object declarations made to achieve the object class of minor changes to a class, and do not need to declare a new subclass.

Object expression

Expression parameter object to realize a method for anonymous inner classes subject by:

window.addMouseListener(object : MouseAdapter() {
    override fun mouseClicked(e: MouseEvent) {
        // ...
    }
    override fun mouseEntered(e: MouseEvent) {
        // ...
    }
})

  Objects can inherit from a base class, or implement other interfaces:

open class A(x: Int) {
    public open val y: Int = x
}

interface B {……}

val ab: A = object : A(1), B {
    override val y = 15
}

If there is a supertype constructor parameters must be passed to it. A plurality of interfaces, and supertypes may be separated by commas.

Class can be defined directly across an object by object expression:

fun main(args: Array<String>) {
    val site = object {
        var name: String = "菜鸟教程"
        var url: String = "www.runoob.com"
    }
    println(site.name)
    println(site.url)
}

 Please note that anonymous object type can be used only in local and declare private scope. If you as a public function's return type or as a type of public properties using anonymous object, the actual type of the function or the type of property would be super anonymous object declaration, and if you do not declare any super-type, it will be Any. Members added in an anonymous object will be inaccessible.

C {class 
    // private function, the return type is an anonymous object type 
    Private Fun foo () {Object = 
        Val X: String = "X" 
    } 

    // public function, the return type is the Any 
    Fun publicFoo () = Object { 
        Val the X-: String = "the X-" 
    } 

    Fun bar () { 
        . Val x1 = foo () the X-// no problem 
        . val x2 = publicFoo () x // error: Could not resolve a reference to "the X-" 
    } 
}

 Objects can be expressed in easy access to other variables scopes: 

 

fun countClicks(window: JComponent) {
    var clickCount = 0
    var enterCount = 0

    window.addMouseListener(object : MouseAdapter() {
        override fun mouseClicked(e: MouseEvent) {
            clickCount++
        }

        override fun mouseEntered(e: MouseEvent) {
            enterCount++
        }
    })
    // ……
}

 

Object declaration

Kotlin using the object keyword to declare an object.

Kotlin, we can easily be obtained by a singleton object declaration.

object DataProviderManager {
    fun registerDataProvider(provider: DataProvider) {
        // ……
    }

    val allDataProviders: Collection<DataProvider>
        get() = // ……
}

Refer to the object, we can directly use its name:  

DataProviderManager.registerDataProvider(……)

Of course, you can also define a variable to obtain acquire the object, then when you define two different variables to get the object, you will find that you can not get two different variables. In other words this way, we get a single case.  

var data1 = DataProviderManager
var data2 = DataProviderManager
data1.name = "test"
print("data1 name = ${data2.name}")  

 In the following examples, the two objects are the same outputs the url:

object Site {
    var url:String = ""
    val name: String = "菜鸟教程"
}
fun main(args: Array<String>) {
    var s1 =  Site
    var s2 = Site
    s1.url = "www.runoob.com"
    println(s1.url)
    println(s2.url)
}

An object can have super type:  

object DefaultListener : MouseAdapter() {
    override fun mouseClicked(e: MouseEvent) {
        // ……
    }

    override fun mouseEntered(e: MouseEvent) {
        // ……
    }
}

Different expression object, when the object is inside another class declaration, the instance of the object and can not be accessed outside the class to the object, but only be accessed via the class name, the same can not directly access the object class to the outside the methods and variables. 

Site Five {class 
    var name = "novice Tutorial" 
    Object the DeskTop { 
        var URL = "www.runoob.com" 
        Fun showname () { 
            Print { "name Desk legs' $"} // error can not be accessed outside the class variables and methods 
        } 
    } 
} 
Fun main (args: the Array <String>) { 
    var = Site Site Five () 
    site.DeskTop.url // error, can not be accessed outside the class instance of the object to 
    site.DeskTop.url // correct 
}

 

Associated Objects

Objects declared inside the class can be labeled with companion keywords, so that it together with associated external class, we will be able to access the internal elements of an object directly by external classes. 

MyClass {class 
    Companion {Object Factory's 
        Fun Create (): MyClass = MyClass () 
    } 
} 

Val instance MyClass.create = () // access to the interior of the object element

We can omit the object name of the object, and then use the Companion alternative to declare the name of the object:  

class MyClass {
    companion object {
    }
}

val x = MyClass.Companion

 

Note: a class which can only declare an internal association objects that keyword companion can only be used once.

Members are invited to look like a static object associated members of other languages, but they are still at runtime instance members of the real object. For example, you can also implement interfaces:

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


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

 

Semantic differences between objects and object declarations expression

There is an important semantic difference between objects and object expressions statement:

  • An object expression is in place using their immediate execution

  • Object declarations are lazy initialization when first accessed to

  • When initialization is associated object is loaded (resolved) in the corresponding class semantic Java static initializer matches

 

 

 

 

 

 

 

 

 

  

Guess you like

Origin www.cnblogs.com/qiangge-python/p/11332885.html