Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Annotation definition throwing error: incompatible types: int[] cannot be converted to int

I have an annotation defined in this way.

    class Lit {
      public static final int[] LIT = {1, 2};
    }

    @interface Buggy {
      int[] vals() default Lit.LIT;
    } 

I am getting this error on compilation error: incompatible types: int[] cannot be converted to int.

while this compiles fine:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

   @interface Buggy {
    int[] vals() default {1, 2};
   } 

What could be the possible reason?

>Solution :

The error message you are getting is not very informative but the actual reason is that annotation defaults must be constant, which is not the case here.

The below example would work because LIT is constant so you can’t change its value:

public class Lit {
    public static final int LIT = 1;
}

@interface Buggy {
    int vals() default Lit.LIT;
}

So for primitive types above approach would work, but not for arrays because arrays are mutable, i.e., for your case I can modify LIT’s values anywhere in the code, like LIT[1] = 5, and then it won’t have the original value.

But if you declare it as

int[] vals() default {1, 2};

it will work because there’s no mutable array variable.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading