I need to write a generic method in the non-generic class. My code looks like the following:
public record Test<T>(T value);
public class MyClass {
public <T> Test<T> getRecord() {
// some method logic
...
switch(type) {
case 1:
return new Test<String>("my string"); // not compile
...
default:
return new Test<Integer>(5); //not compile
}
}
}
The Intellij Idea suggests that I cast it, like this (Test<T>) new Test<Integer>(5), but it is not suitable for me.
Can anyone help to fix that issue?
>Solution :
You are trying to return different types from a single method. Java is a statically typed language, this means that the type of a variable is checked at compile time. Therefore, you can’t return different types from a single method.
To fix your code, you can use wildcard ? to represent an unknown type if you accept to relax type constraints a bit. Below is an example:
public Test<?> getRecord(int type) {
switch(type) {
case 1:
return new Test<String>("my string");
default:
return new Test<Integer>(5);
}
}
// ...
Test<?> record1 = myClass.getRecord(1);
// Test type of record1 and cast it to Test<String> variable
if (record1.value() instanceof String) {
Test<String> tt = (Test<String>) record1;
// ...
}
This way you still maintain some level of typesafety.