Reputation: 61
I want to create a method that can return different data types depending on the action. I, unfortunately, cannot include the real code snippet but with the below one hopefully, you can have an understanding. Basically, I call this method many types with different arguments, and depending on the case it should return a different class. In the real code, all cases have many common parts and only minor differences. Instead of creating different methods for each case, I want to collect them all in one.
Upvotes: 1
Views: 1708
Reputation: 338476
As commented, a method can return only a single value of a single type.
You have at least three three workarounds:
Object
. The calling method tries instanceOf
multiple times to discover the specific type.Animal
abstract class or interface with Dog
and Cat
concrete classes. But does not really make sense for your int
versus String
scenario.The last is now easier in Java 16 with the new records feature. A record is a briefer way to declare a class whose main purpose is to communicate data transparently and immutably. The compiler implicitly creates the constructor, getters, equals
& hashCode
, and toString
.
public record FunkyMathResult( int number , String text ) {}
Instantiate with all but one fields being null.
return new FunkyMathResult( null , String.valueOf( a*b ) ) ;
The calling method then checks each field to find the solitary non-null value.
None of these approaches is recommended. Your situation typically is a sign of a faulty design in your app, a “code smell”. I suggest you consult with someone experienced in object-oriented design regarding your actual problem domain.
Upvotes: 2