Kotlin Learning 13 Object expressions and object declarations

Source: Internet
Author: User
Tags event listener static class
Kotlin Object expressions and object declarations

Kotlin uses object expressions and object declarations to create an object that makes a minor change to a class, and does not need to declare a new subclass.
The object in this article is a keyword, and note that there is no capitalization. I. Object expression 1. Objects that implement an anonymous inner class through an object expression are used in the parameters of the method:

Window.addmouselistener (Object:mouseadapter () {
    override fun mouseclicked (e:mouseevent) {
        //...
    }
    Override Fun Mouseentered (e:mouseevent) {
        //...
    }
})

The above anonymous inner class, like the Android button click event Listener, or ListView item listener event. 2. 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 =
}
3. If the superclass has a constructor, you must pass the argument to it. Multiple super types and interfaces can be separated by commas.

Object expressions allow you to get an object directly by bypassing the definition of a class:

Fun Main (args:array<string>) {
    val site = object {
        var name:string = "Rookie Tutorial"
        var url:string = "Www.run Oob.com "
    }
    println (site.name)
    println (site.url)
}

The above example code can be run directly. 4. Anonymous objects can be used as types that are declared only in local and private scopes.

If you use an anonymous object as the return type of a public function or as a type of public property,
The actual type of the function or property is the super type of the anonymous object declaration.
If you don't declare any super type, it will be any.
Members added to an anonymous object will not be accessible.

Class C {
    //private function, so its return type is anonymous object type
    private Fun foo () = object {
        val x:string = ' x '
    }

    //Public function, so its return type is
    any fun publicfoo () = object {
        val x:string = "x"
    }

    Fun Bar () {
        val x1 = foo (). x        //No problem 
  val x2 = Publicfoo (). x  //Error: Reference "X"} that could not be resolved

A little bit confused, why private method properties can be accessed locally, and common method properties cannot be accessed locally, what is the designer doing? 4. You can easily access other variables in the scope in the expression of an object:

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++
        }
    })
    //...
}
two. Object declaration

Kotlin uses the OBJECT keyword to declare an object. in 1.Kotlin we can easily get a single example through the object declaration.

Object Dataprovidermanager {
    fun Registerdataprovider (provider:dataprovider) {
        //...
    }

    Val alldataproviders:collection<dataprovider> get
        () =//...
}
2. Referring to the object, we can use its name directly:
Dataprovidermanager.registerdataprovider (...)

Of course you can also define a variable to get the object, and when you define two different variables to get the object, you'll find that you don't get two different variables.
In other words, in this way, we get a single example.

var data1 = Dataprovidermanager
var data2 = dataprovidermanager
data1.name = "Test"
print ("Data1 name = ${dat A2.name} ")  
3. Examples

In the following example, two objects output the same URL address:

Object Site {
    var url:string = ""
    val name:string = "Rookie Tutorial"
}
Fun Main (args:array<string>) {
    VA R S1 =  site
    var s2 = site
    s1.url = "www.runoob.com"
    println (S1.url)
    println (s2.url)
}
the output results are:
Www.runoob.com
www.runoob.com
4. Objects can have a super type:
Object Defaultlistener:mouseadapter () {
    override fun mouseclicked (e:mouseevent) {
        //...
    }

    Override Fun Mouseentered (e:mouseevent) {
        //...
    }
}

Unlike object expressions, when an object is declared inside another class, the object cannot be accessed through an instance of an external class.
It can only be accessed through the class name, and the same object cannot directly access the methods and variables of the external class. Sample

Class Site {
    var name = "Rookie Tutorial"
    object desktop{
        var url = "www.runoob.com"
        fun ShowName () {
            //print () Desk Legs $name ")//error, no access to external class methods and variables
            var n=site ()
            println (" Desk Legs ${n.name} ")//correct, create objects yourself to access
        }
    }< c9/>}
Fun Main (args:array<string>) {
    var site = site ()
    //val url=site. Desktop.url//error, cannot be accessed through an instance of an external class to the object
    Val url=site.desktop.url//correct
    println (site.name)
    println (URL)

    //access to desktop internal methods
    Site.DeskTop.showName ()


}
Run Result:
Rookie Tutorials
www.runoob.com
desk Legs Rookie Tutorial

From an example above, you can simply understand that the inner class of object definition is equivalent to a static class. three. object declarations within the associated object 1. Class can be marked with the companion keyword.

So that it is associated with the outer class, and we can access the internal elements of the object directly through the external class.

Class MyClass {
    Companion object Factory {
        fun Create (): MyClass = MyClass ()
    }
}

val instance = Myclas S.create ()   //access to internal elements of an object
2. We can omit the object name of the object and use companion instead of the object name you want to declare:
Class MyClass {
    companion object {
    }
}

val x = myclass.companion

Note: A class can only declare an internal association object, that is, the keyword companion can only be used once. 3. The associated object's members look like static members of other languages, but they are still instance members of real objects at run time.

For example, you can also implement an interface:

Interface Factory<t> {
    fun Create (): T
}


class MyClass {
    companion object:factory< myclass> {
        override fun Create (): MyClass = MyClass ()
    }
}
4. Semantic differences between an object expression and an object declaration

There is an important semantic difference between an object expression and an object declaration:

Object expressions are object declarations that are executed immediately at the place where they are used, when the

initialization of the associated object that is delayed initialization is the first time it is accessed to match the semantics of the

Java static initializer when the corresponding class is loaded (parsed)
5. Example 1
Class MyClass {
    companion object {//companion objects
        var text= "companion object literal"
        fun foo () {
            println ("Method of companion object")
        }       
    }

}



Fun Main (arg:array<string>) {
    val x = myclass.companion//Get Associated object
    println (x.text)   //Get Properties of a Lifetime object
    X.foo ()           //Calling the associated object's method   
}
code Run Results:
Methods of companion object text associated
with object
6. Example 2
Class test{
    var test:string= "Test"
}

interface Factory<t> {//define Interface
    fun Create (): T
}

class MyClass {

     companion object:factory<test> {//Inheritance interface
        override fun Create (): Test = Test ()
    }



Fun Main (arg:array<string>) {
    val x = myclass.companion//Fetch companion object, here is the interface object
    Val y=x.create ()  //Call the interface object's method, get the class test object
    val z=y.test     //Get the properties of the test object
    println ("Result:" +z)
}

code run results;
Result:test

Feeling this Kotlin object expression and object declaration doesn't make much of a difference. It's OK to read one or two examples above.

Can test online if needed: https://blog.csdn.net/wenzhi20102321/article/details/79859347 : Plan and Act

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.