john
john

Reputation: 49

Is it possible to stop implicit conversion?

Just out of curiosity: say i have a method which takes a double value as a parameter if an int is passed to it, it automatically gets converted(or treated as a double. How can in ensure that only numbers of a float format (0.0) are accepted as arguments when the method is called?

Upvotes: 1

Views: 207

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500765

You can't, basically. Not in a really meaningful way. I mean, you could do something horrible like this:

public void method(double x) {
    // This is the method you want to call
}

@Deprecated
public void method(int x) throws PleaseReadTheDocsException {
    throw new PleaseReadTheDocsException("Don't call the method with an int");
}

Then if anyone tries to call method(5) they'll get an error message along the lines of "You need to catch PleaseReadTheDocsException or add a throws clause." But it's really pretty unpleasant, and highly non-idiomatic. Even then, someone can call method((double) 5).

Upvotes: 8

Related Questions