object expression

Sometimes we want to create an object with a slight modification to the current class, but don't want to redeclare a
subclass . Java solves this problem with the concept of anonymous inner classes. Kotlin implements this concept neatly
with .

java implementation

class MyClass
{
    public String name;
    public MyClass(String name)
    {
        this.name = name;
    }
    public void verify()
    {
        System.out.println("verify");
    }
}
public class ObjectExpression
{
    public static void process(MyClass obj)
    {
        obj.verify();
    }
    public static void main(String[] args)
    {
        process(new MyClass("Mary"){
            @Override
            public void verify()
            {
                System.out.println("object verify");
            }
        });

    }
}

Kotlin implementation:
(1) Basic use
If the parent class has a constructor, the corresponding constructor parameters must be passed. Multiple parent classes can be separated by commas, followed by colons

//  对象和委托:对象表达式
//  Kotlin中的对象是为了代替Java中的匿名类
open class KotlinClass(name:String)
{
    open var name = name
    open fun verify()
    {
        println("verify")
    }
}
interface MyInterface
{
    fun closeData()
    {
        println("closeData")
    }
}
fun process(obj:KotlinClass)
{
    obj.verify()
    if(obj is MyInterface)
    {
        obj.closeData()
    }
}
fun main(args: Array<String>)
{
    process(object :KotlinClass("John"),MyInterface{
        override fun verify() {
            println("object verify")
        }
    });
    //  直接建立对象
    fun foo()
    {
        val obj = object
        {
            var x:Int = 10
            var y:Int = 20
        }
        println(obj.x + obj.y)
    }
    foo()
}

(2) An object without a parent class
Sometimes we just need an object without a parent class, we can write:

val adHoc = object {
var x: Int = 0
var y: Int = 0
}
print(adHoc.x + adHoc.y)

(3) Accessing objects in the enclosing scope
Like anonymous inner classes in java, object expressions can access variables in the enclosing scope (unlike java
, these variables do not need to be final modified)

fun countClicks(windows: JComponent) {
var clickCount = 0
var enterCount = 0
window.addMouseListener(object : MouseAdapter() {
override fun mouseClicked(e: MouseEvent) {
clickCount++
}
override fun mouseEntered(e: MouseEvent){
enterCount++
}
})
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325645936&siteId=291194637