Reputation: 17
maybe my problem is stupid, but i can't resolve it.
Here is my code:
public Velocity add(final Velocity velocity)
{
Velocity vel;
if(velocity.getClass().equals(CartesianCoordinate(x, y)))
{
double sumX = x + velocity.x;
double sumY = y + velocity.y;
Velocity v = new Velocity(CartesianCoordinate(x,y));
v.x = sumX;
v.y = sumY;
vel = v;
}
if(velocity.getClass().equals(p))
{
do something...
}
return vel;
}
Can any one tell me why i cant return "vel", i dont want to create a class variable...
Upvotes: 0
Views: 1620
Reputation: 1499770
Can any one tell me why i cant return "vel"
Sure - you haven't given it a value if neither of your conditions is true. The variable isn't definitely assigned, so you can't read its value to return it. What do you want to return in that case? Is it even valid? Perhaps you should throw an exception in that case.
Personally I would actually return from each of the if
blocks - I don't think the local variable is adding any benefit. At that point, it would be more obvious what was wrong:
public Velocity add(final Velocity velocity) {
if (...) {
...
return ...;
}
if (...) {
...
return ...;
}
// What should we do if we get here?
}
Now that both of your conditions which do determine the return value just return it immediately, it's more obvious (IMO) that if you get to the bottom, that's because neither of the conditions has evaluated as true
... so either you want to return some "empty" value, or a null reference, or throw an exception.
Of course, that's assuming that you don't want the second condition to effectively trump the first, which it does at the moment - if both conditions are true, the value set in the first block is presumably irrelevant, as it'll be overwritten by the second block.
It's also unclear what CartesianCoordinate
does, but it's oddly named for a Java method - and if it returns a Class<?>
that's definitely strange. What is p
here? I don't know whether your real code is somewhat different to this, but even aside from the reason this won't compile, it smells fishy to me.
Upvotes: 2
Reputation: 20102
you can only return variables with a value. So there is a case possible where val
does not have one.
The easies way to solve this is to initialize val
directly on the declaration:
Velocity vel = null; //or
Velocity vel = new Velocity();
Or you need to add an else
branch to your if
statement where vel
is initialized also.
if(velocity.getClass().equals(CartesianCoordinate(x, y)))
{
double sumX = x + velocity.x;
double sumY = y + velocity.y;
Velocity v = new Velocity(CartesianCoordinate(x,y));
v.x = sumX;
v.y = sumY;
vel = v;
}else{
vel = null;//or
vel = new Velocity();
}
Upvotes: 0
Reputation: 117569
Local variables have no default values and should be initialized.
If val
was an instance field or a static field and it's not initialized, then it will return the default value when accessing it.
Upvotes: 1