1

Ok, so I've been playing around with this for a little while and I'm starting to believe that generics don't work the same way in Java or I'm missing something. I come from a c# background.

In C#, I might implement a generic interface like so:

public interface ICalculatorOperation<TInput, TOuput>
{
    TOuput RunCalculation(TInput input);
}

public class MyCalculator : ICalculatorOperation<MyCalcInput, MyCalcOutput>
{
    public MyCalcOutput RunCalculation(MyCalcInput input)
    {
        // implemented code ...
    }
}

When I tried to take this same approach in Java, this was my first instinct:

public interface Calculates<TInput, TOutput>{
    <TInput, TOutput> TOutput RunCalculation(TInput input);
}

public class MyCalculator implements Calculates<MyCalcInput, MyCalcOutput>{

    @override
    public MyCalcOuput RunCalculation(MyCalcInput input){ // compile error, doesn't implement interface
        // implemented code ...
    }
}

But as you can see, this won't compile. Even though I set the parameters to the concrete types that I'll being using for this implementation, the compiler still expects to see the actual signature of the interface (sorry, this is weird to me lol).

So I tried this:

public class MyCalculator implements Calculates<MyCalcInput, MyCalcOutput>{

    @override
    public TOuput RunCalculation(TInput input){ 
        MyCalcOutput result = new MyCalcOutput();
        // set the results to this object

        return result; // compile error, return type must be TOutput
    }
}

Now the signature of the method matches that of the interface and the compiler is happy, however now my return statement doesn't work.

It's obvious that there are some differences that I haven't been able to pick up from the docs that I've found on the net or the articles here on SO. I'm hoping someone can shed some light on this?

1 Answer 1

3

Try this interface instead:

public interface Calculates<TInput, TOutput> {
    TOutput RunCalculation(TInput input);
}

(remove the "method local" generic types you have declared, which probably confuses you and/or the compiler).

Then, your initial implementation should work.

PS: It's also convention to use single letter generic types in Java, so <I, O> would be more familiar to Java developers.

Sign up to request clarification or add additional context in comments.

2 Comments

See, it was closer to C# than you thought.. ;-)
I mean come on, we stole the language, it should be pretty close right? lol

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.