Dan2567
Dan2567

Reputation: 33

Creating a method that can return two different things

im trying to make a method that can return two different things based on the type of data that is fed into it.

this class changes the random item to type of data it is

this is what I have, I am aware that in this method that all it is allowed to return is a resource but I'm not sure how to make it that it can return wither a resource or junk.

public Resource itemToResourceOrJunk(randomItem d){
    Resource i;
    Junk O;
    i = d.getResource();
    O = d.getJunk();

    if(d.resourceName.equals("notassigned")){
        return o;
    }
    else if(d.junkName.equals("notassigned")){
        return i;
    }
}

Upvotes: 3

Views: 216

Answers (4)

Igwe Kalu
Igwe Kalu

Reputation: 14868

You could have both Resource and Junk implement same interface (say Stuff), and then make the return type itemToResourceOrJunk to be that interface.

To be clear, it could go this way:

public class Resource implements Stuff { ... }

and

public class Junk implements Stuff { ... }

then

public Stuff itemToResourceOrJunk(randomItem d){ ... }

Though if you need to use methods or properties that are specific to either Resource or Junk, then you'd have to cast to the relevant type.

Upvotes: 4

Gandalf
Gandalf

Reputation: 9855

Make both Resource and Junk implement the same interface (or extend the same class) then use that as the return type.

Upvotes: 2

Wouter
Wouter

Reputation: 4016

Let Resource and Junk implement an interface and use that as the return value.

So

public class Resource implements ResourceOrJunk {
...
}

and

public class Junk implements ResourceOrJunk {
...
}

interface:

public interface ResourceOrJunk {
//can be left empty, or add some shared methods
}

now you can change the method to:

public ResourceOrJunk itemToResourceOrJunk(randomItem d){

and calling methods can check the result:

ResourceOrJunk roj = itemToResourceOrJunk(d);
if (roj instanceof Resource){
    Resource r = (Resource)d;
    //do stuff with resource
} else {
    Junk j = (Jurk)d;
    //do stuff with junk
}

Upvotes: 3

Jason
Jason

Reputation: 11832

You could change your method to return Object:

public Object itemToResourceOrJunk(randomItem d){
    ...
}

Then the caller would have to use instanceof to figure out what type of object was actually returned.

Upvotes: 2

Related Questions