chicka
chicka

Reputation: 61

Can a method return different data types depending on the action?

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.

enter image description here

Upvotes: 1

Views: 1708

Answers (1)

Basil Bourque
Basil Bourque

Reputation: 338476

As commented, a method can return only a single value of a single type.

You have at least three three workarounds:

  • Return an object of type Object. The calling method tries instanceOf multiple times to discover the specific type.
  • Return an object of a more general type, whose actual concrete type is a subclass. This might work for something like Animal abstract class or interface with Dog and Cat concrete classes. But does not really make sense for your int versus String scenario.
  • Return an object of a custom class defined with multiple member fields for which all but one is null.

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

Related Questions