Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Compiler thinks that calling constructor with arg.getClass().cast(arg) is recursive, althought it wrong

I have an interface Commodity, that is a supertype of Item and Consumable enums.
Also, there is a class Option with multiple constructors:

class Option{
    Option(Item c,int price){. . .}
    Option(Consumable c,int price){. . .}
    Option(Commodity c,int price){
        this(c.getClass()!=Commodity.class?c.getClass().cast(c):Item.EMPTY,price);
    }
}
}

Compiler thinks, that this will lead to an infinite recursion, but it obviously won’t.

Recursive constructor invocation Option(Commodity, int)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How to say him "Shut up, guy, I know, what I am doing!"?

>Solution :

Unsurprisingly, the compiler isn’t actually wrong here. Let’s look at the separate parts of your code:

I’m going to assume that both Item and Consumable extend Commodity.

Item.EMPTY: We can assume this is of type Item.

c.getClass().cast(c): This does nothing. It’s always going to be of type Commodity.

c.getClass()!=Commodity.class?c.getClass().cast(c):Item.EMPTY will then resolve to the common supertype. That’s Commodity.

The compiler has no choice but to choose the Commodity overload, and that’s what makes it a recursive call.

All in all, what you are trying to do is call a different constructor overload based on a conditional. That’s simply not possible in Java. Instead, you should make a factory method:

static Option create(Commodity commodity, int price) {
  return commodity instanceof Consumable ? new Option((Consumable) commodity, price) : new Option(Item.EMPTY, price);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading