[英]Non optional property with custom setter Kotlin
I hope someone can help, I am writing moving from java to Kotlin and I want to have a property that it initialised in the init block, that has a custom setter but is non optional. 我希望有人可以提供帮助,我正在编写从Java迁移到Kotlin,我希望有一个属性,它在init块中初始化,有一个自定义setter但不是可选的。
Here is my code below, however this has a warning that tag must be initialised 这是我的代码,但是这有一个警告,标签必须初始化
I would like to make it lateInit, but that means it has to be optional (which I don't want) 我想让它成为lateInit,但这意味着它必须是可选的(我不想要)
class SkiMarker(mapView: MapView, tag:Tag) : Marker(mapView){
var tag:Tag <- ERROR here
set(tag){
this.tag = tag
if(tag != null){
this.mPosition = GeoPoint(tag.lat,tag.lon)
}
}
init {
this.tag = tag
this.mPosition = GeoPoint(tag.lat,tag.lon)
val window = MyInfoWindow(mapView,tag)
this.infoWindow = window
window.subject.observeOn(AndroidSchedulers.mainThread()).subscribe { it ->
setIconForTracking(it)
}
}
}
Many thanks in advance for any comments 非常感谢任何评论
For that logic you only need to use a backing field : 对于该逻辑,您只需使用支持字段 :
class SkiMarker(mapView: MapView, tag:Tag) : Marker(mapView) {
var tag: Tag = tag
set(newTag){
field = newTag // `field` is a keyword
}
}
Note that code like set(newTag) {tag = newTag}
is equivalent to setTag(newTag: Tag) { setTag(newTag) }
where it is actually calling the setter from within itself in a recursion. 请注意,像set(newTag) {tag = newTag}
这样的代码等同于setTag(newTag: Tag) { setTag(newTag) }
,它实际上是在递归中从内部调用setter。
Also, tag
is never null
, so if(tag != null)
is meaningless. 此外, tag
永远不会为null
,因此if(tag != null)
没有意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.