在实现它的类中设置接口的setter

刚开始在android中使用kotlin-

我正在尝试在实现它的类中使用接口的setter –

interface MyInterface { val prop: Int // abstract var propertyWithImplementation: String get() = "foo" set(text){"$text foo"} fun foo() { print(prop) } } class Child : MyInterface { override val prop: Int = 29 override var propertyWithImplementation="bhu" } fun main(args: Array) { println(Child().propertyWithImplementation) } 

输出:BHU

预期产出= bhu foo

我哪里错了?

你正在重写 var ,没有设置它,并且没有在override中使用父设置器,所以它最终没有以任何方式被使用。 设置它看起来像例如

 class Child : MyInterface { override val prop: Int = 29 init { propertyWithImplementation="bhu" } } 

但是如果你这样做,输出将是foo因为这是getter 总是返回的。 setter并没有设置任何东西,只是创建一个字符串而忽略它。

你在接口中没有支持字段,所以你需要将值存储在其他地方,例如

 interface MyInterface { protected var backingProperty: String var propertyWithImplementation: String get() = backingProperty set(text){ backingProperty = "$text foo" } } class Child { override var backingProperty = "foo" } 

解决这个问题。