sf8193
sf8193

Reputation: 635

Returning a generic in java without casting it?

I have an interface like so

public interface ClientBuilder <Client> {

    Client build();

}

and it's being used in a function like this

private static Service createImpl(ClientBuilder clientBuilder) {
        return new serviceImpl((x) clientBuilder.build());
    }

Is there a way where I wouldn't have to type cast it, so that I can remove the (x)? It's not entirely necessary, just would be a nice to have

Upvotes: 0

Views: 38

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201537

Yes. You make ClientBuilder generic in the function. And, you should follow Java naming conventions. serviceImpl looks like a method name (and x looks like a variable not a class name). But using your names, something like

private static Service createImpl(ClientBuilder<x> clientBuilder) {
    return new serviceImpl(clientBuilder.build());
}

Upvotes: 2

Related Questions