Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does returning an int in a method that should return a short work?

Tags:

static void method(short x)
{
   //do some stuff
}

When I called above method from main method using the following line.

method(1); // compilation failed

I know above calling is invalid because parameter 'x' is expecting short and we are passing int.

I further tested the above concept and coded another method:

static short method()
{
    //do some stuff
    return 1;    
}

but above method works fine, where return type is short and we are returning int. Why does the second method compile?

like image 463
Vijendra Singh Avatar asked May 27 '13 09:05

Vijendra Singh


1 Answers

The return statement (JLS 14.17) is able to use an assignment conversion (JLS 5.2) to convert from the original expression type to the return type.

Assignment conversion includes the ability to convert a constant expression to a narrower type if it's in the range of the target type. So a constant expression of type int can be converted to short when the value is in the range of short.

Method arguments don't go through assignment conversion - they only use method invocation conversion (JLS 5.3) which doesn't include this constant conversion.

In terms of why this happens - I suspect it just makes things simpler to reason about. Assignment conversions always have a single target type - whereas in the case of method arguments, there may be various different overloads to consider, so there'd have to be more rules to determine how specific a constant expression conversion would be. That's just a guess though - and it clearly could be done. (C# allows this, for example.)

like image 110
Jon Skeet Avatar answered Jan 11 '23 02:01

Jon Skeet