0

In this video, I saw that the programmer used a return statement of this form in a static method:

public static int staticFunc(int x, int y) {
    return x = y;
}

(This is not the exact function, which can be found at 10:11 in the video)

Why is this (assigning a variable in a return statement) used instead of simply returning x? And what is the name of this type of statement?

additional context: the video is about making games in java, and the method in the video is specified in the game object to allow a player object to only move in the bounds of the window. This function is used to update a property in the player object.

efong5
  • 366
  • 1
  • 6
  • 21
  • Disclaimer: I understand that it is very likely a question like this has been asked before, however it does not show up in the ways that I am looking for it, so hopefully we can route this to an existing answer – efong5 Dec 10 '17 at 02:17
  • 6
    This just returns y. It is a silly example. – Captain Giraffe Dec 10 '17 at 02:20
  • `int x` is a call-by-value argument. So assigning it before the return has no effect. – lurker Dec 10 '17 at 02:22

2 Answers2

0

There's no good reason I can think of to write it that way, especially since Java is call-by-value, i.e. assigning an input to something new inside the body of a function won't change that variable outside the scope of the function.

It makes me think the person in that video just has a poor understanding of that fact.

In other contexts, the result of an assignment expression is the value that is assigned to the variable, so you can do things like

String someName = "Tom";
System.out.println(someName = "John");

and it will print John to the console, as well as assign "John" to someName.

But in the context of your function, there's no good reason to do it the way presented in the video.

tredontho
  • 1,273
  • 10
  • 14
-1

....[W]hat is the name of this type of statement?

"Silly", "frustrating", "amateurish", or my personal favorite: "unnecessary".

There's no reason to do what the author of the code is doing there. The only thing that will happen is that you will be returning y, which raises the question of why the method exists in the first place.

There are valid cases in which you would want to use an assignment operator in a specific context - namely, if you wanted to use a throwaway variable to process something for you, but in this context, there's nothing being gained from this except a lot of confusion for anyone else reading the code.

While I can't speak to the video, I'd recommend - if you need a statement like this - to use a Function instead to do your transformation, if it's necessary at all.

Makoto
  • 104,088
  • 27
  • 192
  • 230