Since there is no concept of static members in Kotlin, Kotlin introduces an interesting syntactic sugar: objects. So can objects replace static class members? How do you do that? More on that below.

Object expression

In Java, there is also the concept of anonymous classes, that is, when creating a class, you do not need to specify the name of the class. Anonymous classes are typically used for method parameters. The basic idea is that a method needs to receive an instance of a class or interface that is only used in the method; there is no need to define a separate class or create an object variable. Therefore, an instance of the class is created at the same time as the method parameter values are passed in. Example code is as follows:

public class JClass {

    public void fun(){
        System.out.println("jclass"); }}Copy the code
public class JClassTest {

    public static void process(JClass jClass) {
        jClass.fun();
    }

    public static void main(String[] agrs) {
        process(new JClass() {
            @Override
            public void fun() {
                System.out.println("haha jclass"); }}); }}Copy the code

The final output is haha jClass

Similar functionality exists in Kotlin, but instead of anonymous classes, objects. With the same functionality as above, here is the Kotlin code:

object JClassTest {

    fun process(jClass: JClass) {
        jClass.`fun`()
    }

    @JvmStatic
    fun main(agrs: Array<String>) {
        process(object : JClass() {
            override fun `fun`() {
                println("haha jclass")}})}}Copy the code

As you can see, to create an object, you use the object keyword, and the class that the object inherits needs to be separated from object by a colon (:).

An object, like a class, can have only one parent class, but can implement multiple interfaces. In the following code, the object not only inherits the JClass class, but also implements the JInterface interface:

process(object : JClass(), JInterface {
	override fun printlnData() {
		println("haha jinterface")
	}

	override fun `fun`() {
		println("haha jclass")}})Copy the code

If you just want to create an object and don’t want to inherit any classes or implement any interfaces, you can do this:

var data = object {
	var value: String = "H"
}
Copy the code

Declare anonymous Objects

Anonymous objects can only be used in local (function) or private declarations. If anonymous objects are used for the return value of a public function or the type of a public property, the Kotlin compiler redefines the return type of those functions or properties as the parent type of the anonymous object. If the anonymous object does not inherit from Any class or implement Any interface, the parent type is Any. Therefore, any members added to the anonymous object will not be accessible.

X private fun foo() = object {var x = 1} // public So the return type of the function is Any public fun publicFoo() = object {var x = 2} funbar() {var x = foo().x // can access // var x2 = publicFoo().x // compiled error, publicFoo returns Any object}}Copy the code

Access variables in the enclosing scope

In Java, when an anonymous object accesses a variable ina closed scope, the variable needs to be declared with final, which means that the value of a variable ina closed scope cannot be modified in an anonymous object. In Java8, if you only use a variable ina closed scope, you do not need final. However, if you change the value of a variable, you must use final. In Java8, a closed scoped variable is an implicit final variable.

In Kotlin, however, a variable in a closed scope can be accessed arbitrarily within an anonymous object, including modifying its value:

    fun main(agrs: Array<String>) {
        var n = 10
        process(object : JClass(), JInterface {
            override fun printlnData() {
                println("$n")
                println(n++)
            }
        })
    }
Copy the code

Accompany the object

There is no concept of a static class member in Kotlin, but that doesn’t mean you can’t implement something similar to a static class member. The companion object is the grammatical sugar Kotlin uses to solve this problem.

If you define an object in a Kotlin class, you call that object the companion of that class. Companion objects are declared using the companion keyword:

class CompanionClass {

    companion object {
        val TAG = "JIA"

        fun create(): CompanionClass = CompanionClass()
    }

}
Copy the code

Members defined in the companion object are directly accessible by class name.

var instance=CompanionClass.create()
Copy the code

Note that while the members of companion objects look like static members of classes in other languages, they are still members of instances of real objects at run time, and they are different from static members. However, with @jVMtatic annotations, the Kotlin compiler compiles them to Byte Code’s true static methods. More on this later.

More exciting content, welcome to pay attention to my wechat public number – Android motor vehicle