Ben*_*rth 8 properties getter-setter kotlin
在Kotlin接口中,使用空的get/set语句声明属性是否重要?
例如...
interface ExampleInterface {
// These...
val a: String
get
var b: String
get
set
// ...compared to these...
val c: String
var d: String
}
Run Code Online (Sandbox Code Playgroud)
我很难注意到差异.
在实现接口时,如果我对属性使用getter/setter,或者直接设置值,似乎并不重要.
当通过java访问这些时,val它们都有getter,而且var它们都有getter和setter.
public void javaMethod(ExampleInterface e) {
e.getA();
e.getB();
e.setB();
e.getC();
e.getD();
e.setD();
}
Run Code Online (Sandbox Code Playgroud)
hot*_*key 10
在您的示例中的属性声明是相同的,get并且set可以从那里被安全地移除,因为,当你正确地指出,无论如何都会产生的存取.但是,with get和的语法set可用于提供访问器实现或限制其可见性.
提供实施:
interface ExampleInterface {
var b: String
get() = ""
set(value) { }
}
Run Code Online (Sandbox Code Playgroud)
此示例显示了在接口中声明的属性的默认实现.在接口实现中仍然可以覆盖此属性.
class Example {
var b: String = ""
get() = "$field$field"
}
Run Code Online (Sandbox Code Playgroud)
这里,get() = ...覆盖具有支持字段的属性的默认getter行为,set而未提及,因此它的行为正常.
可见性限制:
class Example {
var s: String = "s"
private set
}
Run Code Online (Sandbox Code Playgroud)
在此示例中,setter可见性为private.可见性get始终与属性的可见性相同,因此无需单独指定它.接口无法声明private成员.
abstract class Example {
abstract var b: String
protected set // Restrict visibility
}
Run Code Online (Sandbox Code Playgroud)
此属性的setter仅限于此类及其子类.接口无法声明protected成员.
当然,访问器实现可以与可见性限制相结合:
class Example {
var s: String = "abc"
private set(value) { if (value.isNotEmpty()) field = value }
}
Run Code Online (Sandbox Code Playgroud)
也可以看看:
| 归档时间: |
|
| 查看次数: |
2960 次 |
| 最近记录: |