Vlad A
Vlad A

Reputation: 154

How do I create a method in Java that returns an enum depending on input?

I have two enums

public enum CurrencyOptionEUR {
  EUR_EUR("euro"),
  EUR_GBP("pound");
}

and

public enum CurrencyOptionAsia {
  ASIA_YEN("yen"),
  ASIA_EUR("euro");
}

and their values might overlap as the example show.

What I want is a method that based on an argument returns one or the other enum. Something like this

public enum switchEnum(String country){
    if(country.equals("Japan")) return CurrencyOptionAsia;
    else return CurrencyOptionEur;
}

but enum cannot be the return type of a method

What would the best way to implement this behavior? Thanks

Upvotes: 0

Views: 147

Answers (3)

Aakash Sorathiya
Aakash Sorathiya

Reputation: 11

All enums implement the interface Enum, so you can certainly write a method that returns an enum this way.

public Enum<?>[] switchEnum(String country) {
    if(country.equals("Japan")) return CurrencyOptionAsia.values();
    else return CurrencyOptionEur.values();
}

Upvotes: 0

Jeroen Steenbeeke
Jeroen Steenbeeke

Reputation: 4013

Java is a strongly typed language, so all variables and return types are required to have an actual type. With this in mind, I would recommend having both enums implement a common interface:

interface CurrencyOption {
}

Then modifying your existing enums as follows:

public enum CurrencyOptionEUR implements CurrencyOption {
  // Contents omitted for brevity
}

// Probably should rename this one for consistency
public enum CurrencyAsia implements CurrencyOption {
  // Contents omitted for brevity
}

And then using CurrencyOption[] as your return type:

public CurrencyOption[] switchEnum(String country){
    if(country.equals("Japan")) return CurrencyAsia.values();
    else return CurrencyOptionEur.values();
}

With that said I would like to point out Java has had built-in support for currencies since version 1.4, and I would strongly recommend using this (or another existing library) instead of creating your own.

Upvotes: 4

maio290
maio290

Reputation: 6732

I had the same problem: You have to return an Object and then check for the instance in your calling method and parse it accordingly.

But for your example, I wouldn't take this approach anyway. Java has a own Currency class, I'd rather work with that one, since it features getSymbol() and getDisplayName(). So instead of returning an enum, you'd return a Set of currencies.

Upvotes: 1

Related Questions