【发布时间】:2018-10-11 11:06:43
【问题描述】:
我一直在尝试了解如何将 @IntRange(from = 1) 应用于我的 Kotlin 属性。经过几次失败的尝试,我终于在 Java 中创建了我想要的类,并将其转换为 Android Studio 中的 Kotlin。这是我的 Java 类:
import android.support.annotation.IntRange;
public class SimpleThing {
private int val;
@IntRange(from = 1)
public int getVal() {
return val;
}
public void setVal(@IntRange(from = 1) int val) {
this.val = val;
}
}
这是我从 Android Studio 得到的自动转换:
import android.support.annotation.IntRange
class SimpleThing {
@get:IntRange(from = 1)
var `val`: Int = 0
}
@IntRange 似乎适用于 getter,但不适用于 setter。是否可以将此注释应用于设置器,以便出现适当的 lint 警告。目前我刚刚重写了 set 方法来抛出这样的 IllegalArgumentException:
@get:IntRange(from = 1)
var rowSize: Int = 3
set(value) {
if (value < 1) throw IllegalArgumentException("row size must be at least 1")
field = value
notifyDataSetChanged()
}
我已经尝试添加@set:IntRange(from = 1),但我收到错误This annotation does not apply for type void,因为它试图将@IntRange 应用于返回值(在setter 的情况下是无效的)而不是setter 参数。
【问题讨论】:
标签: android kotlin android-annotations android-lint kotlin-interop