How can I create a AutoValue class with generics?

866 Views Asked by At

I would like to have a data class using AutoValue and one of the property is generic, wondering what I am doing wrong ?

public abstract class Data<T> {

    public static <T> Data createData(T value, Integer index) {
        return new AutoValue_Data<T>(value, index);
    }

    @NotNull
    public abstract T value();

    @NotNull
    public abstract Integer index();
}
2

There are 2 best solutions below

0
Louis Wasserman On BEST ANSWER

Your code looks like it should work, with one line that should get a warning fixed:

public static <T> Data createData(T value, Integer index) {

should be

public static <T> Data<T> createData(T value, Integer index) {
0
Chiara Tumminelli On

You forgot generic T after Data, your code should be:

public abstract class Data<T> {

    public static <T> Data <T> createData(T value, Integer index) {
        return new AutoValue_Data<T>(value, index);
    }

    @NotNull
    public abstract T value();

    @NotNull
    public abstract Integer index();
}