var status
private get
无法正常工作并出现错误:Getter visibility must be the same as property visibility
在我的情况中,原因是为了Java互操作性:我希望我的Java代码能够调用setStatus
但不能调用getStatus
。
var status
private get
无法正常工作并出现错误:Getter visibility must be the same as property visibility
在我的情况中,原因是为了Java互操作性:我希望我的Java代码能够调用setStatus
但不能调用getStatus
。
在当前的 Kotlin 版本(1.0.3)中,唯一的选项是拥有单独的 setter 方法,如下所示:
class Test {
private var name: String = "name"
fun setName(name: String) {
this.name = name
}
}
如果您希望限制外部库访问getter,可以使用internal
可见性修饰符,在库中仍然可以使用属性语法:
class Test {
internal var name: String = "name"
fun setName(name: String) { this.name = name }
}
fun usage(){
val t = Test()
t.name = "New"
}
class WriteOnly {
private var backing: Int = 0
var property: Int
@Deprecated("Property can only be written.", level = DeprecationLevel.ERROR)
get() = throw NotImplementedError()
set(value) { backing = value }
val exposed get() = backing // public API
}
使用方法:
val wo = WriteOnly()
wo.property = 20 // write: OK
val i: Int = wo.property // read: compile error
val j: Int = wo.exposed // read value through other property
使用“获取属性:Int”的方法是错误的。属性只能被写入。
The main use case are obviously APIs that allow properties to be written, but not read:
user.password = "secret"
val pw = user.password // forbidden
Another scenario is a property which modifies the internal state, but is not stored itself as a field. (Could be done more elegantly using different design).
body.thrust_force = velocity
body.gravity_force = Vector(0, 0, 9.8)
// only total force accessible, component vectors are lost
val f = body.forces
This pattern is also useful for DSLs of the following kind:
server {
port = 80
host = "www.example.com"
}
In such cases, values are simply used as one-time settings, and the write-only mechanism described here can prevent accidentally reading a property (which might not be initialized yet).
由于此功能并非为此用例设计,因此存在一定的限制:
If accessed using a property reference, the compile-time error turns into a runtime error:
val ref = wo::property
val x = ref.get() // throws NotImplementedError
The same is true for reflection.
This functionality cannot be outsourced into a delegate, because an error-deprecated getValue()
method cannot be used with by
.
getX/setX
方法更加冗长,并且可能会引发“为什么没有属性?”这样的问题,这在 Kotlin 中是惯用语。一个很好但相对较小的副作用是:如果 Kotlin 引入了只写属性,那么调用站点语法已经是正确的 ;) - TheOperator