没有领域的Kotlin getter setter

时间:2017-10-25 08:54:42

标签: properties kotlin field

我想创建一个没有字段的getter和setter。目前我有这个功能:

/** Only the color component will be considered, alpha has no effect */ 
fun setCircleColor(@ColorInt color : Int){
    circlePaint.color = ColorUtils.setAlphaComponent(color, circlePaint.alpha)
}

理想情况下,我希望有类似的东西

circleColor: @ColorInt Int 
  get(){
    return circlePaint.color
  set(value){
    circlePaint.color = ColorUtils.setAlphaComponent(color, circlePaint.alpha)
  }

正如您所看到的,我不想将circleColor存储在var中,但却可以调用

myView.color = 0xFFaaaaaa 而不是myView.setColor(0xFFaaaaaa)。这可能吗?

1 个答案:

答案 0 :(得分:2)

我建议您按照您打算这样做的方式实施它:

var circleColor: Int
    @ColorInt get() = circlePaint.color
    set(@ColorInt color) {
        circlePaint.color = ColorUtils.setAlphaComponent(color, circlePaint.alpha)
    }