Why is not possible to create a local record that contains fields corresponding to the generic type of the method?
Not working example:
public class Test {
<T> void foo(T param) {
record Container(T content) { }
Container test = new Container(param);
}
}
I get the error: non-static type variable T cannot be referenced from a static context.
Working but in my opinion unnecessary:
public class Test {
<T> void foo(T param) {
record Container<S>(S content) { }
Container<T> test = new Container<>(param);
}
}
A record isn't just a drop in replacement of a class.
public class Recorded<T>{
class Bc{
T t;
}
record Br(T t){};
}
The class will compile file, but the record fails because
| non-static type variable T cannot be referenced from a static context
| record Br(T t){};
That is because records cannot be inner classes, or they are implicitly static.
For OP's case, the record is being limited in scope but it obeys the same rules. Essentially, since a record is not an inner class you cannot make a concrete type from a generic.
Here is the related question about interfaces