Kotlin Object expressions and object declarations
Kotlin uses object expressions and object declarations to implement an object that creates a class that makes minor changes to a class, and does not need to declare a new subclass. an object expression
An object that implements an anonymous inner class through an object expression is used in the parameters of the method:
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 = +
}
If the superclass has a constructor, you must pass the parameter to it. Multiple hyper-types and interfaces can be separated by commas.
Object expressions allow you to get an object directly over 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)
}
Note that anonymous objects can be used as types that are declared only on local and private scopes. If you use an anonymous object as the return type of a public function or as a type of a public property, the actual type of the function or property is the super-type of the anonymous object declaration, or any if you do not declare any of the superclass types. Members added in the 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 a NY fun
publicfoo () = object {
val x:string = ' x '
} Fun
Bar () {
val x1 = foo (). x //No problem
Val x2 = Publicfoo (). x //error: Failed to resolve reference "X"
}
}
Other variables in the scope can be easily accessed in object representations:
Fun Countclicks (window:jcomponent) {
var clickcount = 0
var entercount = 0
Window.addmouselistener (object: Mouseadapter () {
override mouseclicked (e:mouseevent) {
clickcount++
} override fun
mouseentered ( e:mouseevent) {
entercount++
}
})
//...
}
Object Declaration
Kotlin uses the OBJECT keyword to declare an object.
In Kotlin we can easily get a singleton by object declaration.
Object Dataprovidermanager