I have been trying to find out how to apply @IntRange(from = 1)
to my Kotlin property. After several failed attempts I finally just created the class I wanted in Java and converted it to Kotlin inside Android Studio. Here is my Java class:
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;
}
}
and this is the automatic conversion I got from Android Studio:
import android.support.annotation.IntRange
class SimpleThing {
@get:IntRange(from = 1)
var `val`: Int = 0
}
The @IntRange
appears to get applied to the getter but not to the setter. Is it possible to apply this annotation to the setter also so that the appropriate lint warning will appear. Currently I have just overridden the set method to throw an IllegalArgumentException like this:
@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()
}
I have already tried adding @set:IntRange(from = 1)
but I get the error This annotation does not apply for type void
because it is trying to apply @IntRange
to the return value (which is void in the case of the setter) as opposed to the setter argument.
If you need to annotate the primary constructor of a class, you need to add the constructor keyword to the constructor declaration, and add the annotations before it: class Foo @Inject constructor(dependency: MyDependency) { ... }
Annotations are used to attach metadata to classes, interface, parameters, and so on at compile time. Annotation can be used by compiler which reflects at runtime. We can change the meaning of the data or program according to annotation values.
The @setparam
annotation appears to be what I'm looking for, but no lint warning is raised in Android Studio when I try to assign a value outside the range.
Here is my new code:
@get:IntRange(from = 1)
@setparam:IntRange(from = 1)
var rowSize: Int = 3
set(value) {
if (value < 1) throw IllegalArgumentException("row size must be at least 1")
field = value
notifyDataSetChanged()
}
and here is where I would normally expect to see a lint warning telling me I am assigning a value outside the int range
However the lint warning does appear when using the SimpleThing class in Kotlin code
The lint warning also does not appear when calling the Kotlin method as Java code
It would appear that this functionality is just not implemented yet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With