10
votes

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.

2

2 Answers

5
votes

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

enter image description here

However the lint warning does appear when using the SimpleThing class in Kotlin code

enter image description here

The lint warning also does not appear when calling the Kotlin method as Java code

enter image description here

It would appear that this functionality is just not implemented yet.

0
votes

Not in the position to test this currently, but have you tried adding a @set like so:

@set:IntRange(from = 1)
@get:IntRange(from = 1)
    var `val`: Int = 0