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

How can I write a generic method?

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?

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

>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.

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