1

I'm trying to take 2 values and cast them to Integer or Double, but I'm unable to do so in a simple manner as described below, because the variable declaration can't be done inside a block statement:

if (args.get(0) instanceof Integer) {
    Integer left = (Integer) args.get(0);
} else {
    Double left = (Double) args.get(0);
}

if (args.get(1) instanceof Integer) {
    Integer right = (Integer) args.get(1);
} else {
    Double right = (Double) args.get(1)
}

return left + right; // this is not allowed

Of course, a trivial solution would be to exhaust all 4 combinations:

if (args.get(0) instanceof Integer && args.get(1) instanceof Integer) {
    return ((Integer) args.get(0)) + ((Integer) args.get(1));
} else if ...

However, I assume there is a simple and well-known design pattern to achieve what I want much more eloquently.

9
  • 1
    Perfect link: stackoverflow.com/questions/9205131/… (related stackoverflow.com/questions/19463138/… also stackoverflow.com/questions/16040556/…) Commented May 6, 2016 at 17:56
  • 1
    Why not just cast everything to double? Commented May 6, 2016 at 17:56
  • @dbugger: Because I would like 2+3=5, not 2+3=5.0 Commented May 6, 2016 at 17:59
  • 1
    @Tunaki. Thank you for your response. I'm however unable to see how the link you provided could help my case. Double and Integer are both derived from Number, but I can't add 2 instances of Number together with a binary operator. What am i missing? Commented May 6, 2016 at 18:02
  • Going through an awful lot of work to do something that is easily handled by formatting the result as needed. Commented May 6, 2016 at 18:03

1 Answer 1

5

You don't have to exhaust all 4 options, because only one of them results in an integer:

Number left = (Number)args.get(0);  // not sure if casting is necessary here
Number right = (Number)args.get(1); // since I don't know the type of your list
if (left instanceof Integer && right instanceof Integer) {
    // if both operands are Integer, return an Integer
    return left.intValue() + right.intValue();
} else {
    // if any of the operands is Double, the result must be Double
    return left.doubleValue() + right.doubleValue();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.