从方法访问委托对象

时间:2018-08-18 10:24:35

标签: kotlin delegates

考虑以下Kotlin代码:

class Derived(n1: String, n2:String) : Teacher by TeacherImp(),Person by PersonImpl(n1, n2) {
     // desire to call method of PersonImp object... possible??
}

有什么方法可以访问委托对象实例?

考虑派生类是否要访问委托的方法。

1 个答案:

答案 0 :(得分:3)

您可以将委托保存到私有不可变属性中,例如:

interface Teacher {
    fun sayHelloTeacher() = println("Teacher hello")
}

interface Person {
    fun sayHelloPerson() = println("Person hello")
}

class TeacherImp : Teacher {
    fun sayHelloTeacherImp() = println("TeacherImp hello")
}

class PersonImp(val n1: String, val n2: String) : Person {
    fun sayHelloPersonImp() = println("PersonImp hello $n1 $n2")
}

class Derived private constructor(private val t: TeacherImp, private val p: PersonImp) : 
    Teacher by t, Person by p {

    constructor(n1: String, n2: String) : this(TeacherImp(), PersonImp(n1, n2))

    init {
        sayHelloPerson()
        sayHelloTeacher()
        t.sayHelloTeacherImp()
        p.sayHelloPersonImp()
    }
}

fun main(args: Array<String>) {
    Derived("first", "second")
}

通过此实现,唯一的公共构造函数与原始构造函数相同,并且调用存储实际对象的私有构造函数。

注意:通过反射,无需额外的构造函数就可以访问它们,但是我认为这是解决问题的直接方法。