Specific use of object expressions and object declarations in kotlin

The main difference between kotlin's object expression and anonymous inner class in Java: anonymous inner class can only specify one parent type, but object expression can specify 0 ~ n parent types@ H_ 502_ 1@

1、 Object expression @ h_ 502_ 1@

The syntax format of object expression is as follows: @ h_ 502_ 1@

object [: 0~N个父类型]{
  //对象表达式的类体部分
}

The object expression also has the following rules: @ h_ 502_ 1@

package `0705`

interface Outputable {
  fun output(msg: String)
}

abstract class Product(var price: Double) {
  abstract val name: String
  abstract fun printInfo()
}

fun main(args: Array<String>) {
  //指定一个父类型(接口)的对象表达式
  var ob1 = object : Outputable {
    override fun output(msg: String) {
      for (i in 1..6) {
        println("<h${i}>${msg}</h${i}>")
      }
    }
  }
  ob1.output("随便输出点什么吧")
  println("-----------------------------------------------")
  //指定零个父类型的对象表达式
  var ob2 = object {
    //初始化块
    init {
      println("初始化块")
    }

    //属性
    var name = "Kotlin"

    //方法
    fun test() {
      println("test方法")
    }

    //只能包含内部类,不可以包含嵌套类
    inner class Inner
  }
  println(ob2.name)
  ob2.test()
  println("-----------------------------------------------")
  //指定两个父类型的对象表达式
  var ob3 = object : Outputable,Product(1.23) {
    override fun output(msg: String) {
      println("输出信息:${msg}")
    }

    override val name: String
      get() = "激光打印机"

    override fun printInfo() {
      println("高速极光打印机们支持自动双面打印!")
    }
  }
  println(ob3.name)
  ob3.output("Kotlin慢慢学")
  ob3.printInfo()
}

Output result: @ h_ 502_ 1@

Kotlin's object expression can be divided into two cases: @ h_ 502_ 1@

package `0705`

class ObjectExprType {
  private val ob1 = object {
    val name: String = "Kotlin"
  }
  internal val ob2 = object {
    val name: String = "Kotlin"
  }
  private fun privateBar()=object {
    val name:String="Java"
  }
  fun publicBar()=object {
    val name:String="Java"
  }
  fun test(){
    //ob1是private对象表达式,编译器可识别它的真实类型
    println(ob1.name)
    //ob2是非private对象表达式,编译器当它是Any类型
//    println(ob2.name)
    //privateBar是private函数,编译器可识别它返回的对象表达式的真实类型
    println(privateBar().name)
    //publicBar是非private函数,编译器将它返回的对象表达式当成Any类型
//    println(publicBar().name)
  }
}

fun main(args: Array<String>) {
  ObjectExprType().test()
}

Output result: @ h_ 502_ 1@

The kotlin compiler recognizes the real type of private object expressions@ H_ 502_ 1@

Kotlin's object expression can access or modify local variables within its scope@ H_ 502_ 1@

fun main(args: Array<String>) {
  var a = 20
  var obj = object {

    fun change() {
      println("change()方法修改变量a的值")
      a++
    }
  }
  obj.change()
  println(a)
}

Output result: @ h_ 502_ 1@

Kotlin's object expression is enhanced in three aspects over Java's anonymous inner class: @ h_ 502_ 1@

2、 Object declaration and singleton pattern @ h_ 502_ 1@

The syntax format of object declaration is as follows: @ h_ 502_ 1@

object ObjectName [: 0~N个父类型]{
  //对象表达式的类体部分
}

The syntax of object declaration is very similar to that of object expression. The difference is that the object expression has no name after the object keyword; The object declaration needs to specify a name after the object keyword@ H_ 502_ 1@

There are also the following differences between the two: @ h_ 502_ 1@

package `0705`

interface Outputable {
  fun output(msg: String)
}

abstract class Product(var price: Double) {
  abstract val name: String
  abstract fun printInfo()
}

//指定一个父类型的对象表达式
object MyObject1 : Outputable {
  override fun output(msg: String) {
    for (i in 1..6) {
      println("<h${i}>${msg}</h${i}>")
    }
  }
}

//指定零个父类型的对象表达式
object MyObject2 {
  //初始化块
  init {
    println("初始化块")
  }

  //属性
  var name = "Kotlin"

  //方法
  fun test() {
    println("test方法")
  }

  //只能包含嵌套类,不可以包含内部类
  class Inner
}

//指定两个父类型的对象表达式
object MyObject3 : Outputable,Product(1.23) {
  override fun output(msg: String) {
    println("输出信息:${msg}")
  }

  override val name: String
    get() = "激光打印机"

  override fun printInfo() {
    println("高速极光打印机们支持自动双面打印!")
  }
}

fun main(args: Array<String>) {

  MyObject1.output("一起来学Kotlin")
  println("-----------------------------------------------")
  println(MyObject2.name)
  MyObject2.test()
  println("-----------------------------------------------")
  println(MyObject3.name)
  MyObject3.output("Kotlin真不错")
  MyObject3.printInfo()
}

Output result: @ h_ 502_ 1@

The object declaration is specially used to implement the singleton pattern. The object defined by the object declaration is the only instance of the class. The program can directly access the only instance of the class through the name of the object declaration@ H_ 502_ 1@

3、 Companion objects and static members @ h_ 502_ 1@

The object declaration defined in the class can be decorated with company, so that the object becomes an associated object@ H_ 502_ 1@

Each class can only define one associated object at most. The associated object is equivalent to the object of the external class. The program can directly call the members of the associated object through the external class@ H_ 502_ 1@

package `0705`

interface CompanionTest {
  fun output(msg: String)
}

class MyClass {
  //使用companion修饰的伴生对象
  companion object MyObject1 : CompanionTest {
    val name = "name属性值"
    override fun output(msg: String) {
      for (i in 1..6) {
        println("<h${i}>${msg}</h${i}>")
      }
    }
  }
}

fun main(args: Array<String>) {
  //使用伴生对象所在的类调用伴生对象的方法
  MyClass.output("Kotlin必须学")
  println(MyClass.name)
}

Output result: @ h_ 502_ 1@

The main function of the associated object is to simulate static members for its external class, but it is only simulation. The members of the associated object are still instance members of the associated object itself and do not belong to the external class of the associated object@ H_ 502_ 1@

4、 Extension @ h of companion object_ 502_ 1@

Companion objects can also be extended. If a class has companion objects, kotlin allows you to extend methods and properties for companion objects@ H_ 502_ 1@

package `0705`

interface CompanionTest {
  fun output(msg: String)
}

class MyClass {
  //使用companion修饰的伴生对象
  companion object : CompanionTest {
    val name = "name属性值"
    override fun output(msg: String) {
      for (i in 1..6) {
        println("<h${i}>${msg}</h${i}>")
      }
    }
  }
}

//为伴生对象扩展方法
fun MyClass.Companion.test() {
  println("为伴生对象扩展的方法")
}

val MyClass.Companion.foo
  get() = "为伴生对象扩展的属性"

fun main(args: Array<String>) {
  //使用伴生对象所在的类调用伴生对象的方法
  MyClass.output("Kotlin必须学")
  println(MyClass.name)
  //通过伴生对象所在的类调用为伴生对象扩展的成员
  MyClass.test()
  println(MyClass.foo)

}

Output result: @ h_ 502_ 1@

The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot@ H_ 502_ 1@

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>