Why declare a function argument to be final?

2019-01-10 17:03发布

问题:

I'm currently working my way through the book "Teach Yourself Android Application Development in 24 Hours" published by Sams. I'm relatively new to Java, Android or otherwise. I have a very solid background in ActionScript 3, which has enough similarities with Java that the language itself isn't hard to grasp, but I do still have some questions about the rationale behind some of the code samples in the book. For example, here's a function that comes with the sample code for Hour 9:

private void processScores(final TableLayout scoreTable, 
      XmlResourceParser scores) throws IOException, XmlPullParserException{

In this function signature, the authors have declared the scoreTable argument as final. I'm a little puzzled as to why they did this. It wouldn't cross my mind to even attempt to assign a new value to the function argument scoreTable (it's considered a bad practice in ActionScript). Further, I haven't actually seen anyone do this in any of the real-world Java I've examined or ported into AS3.

Is there something specific about Android development that makes it a necessity to sometimes declare certain function arguments as final?

Why is the TableLayout object declared final, but not the XmlResourceParser?

回答1:

There are two main reasons you might want to mark an argument final. First, if you're planning on using the argument in an anonymous inner class, then you must mark it final so that it can be referenced in that class. This is actually a pretty common use case for marking arguments final.

The other common reason to mark arguments final is to prevent yourself from accidentally overwriting them. If you really don't want to change the arguments, then perhaps you should mark them final so that if you actually do, you'll get the error at compile-time rather than finding out at runtime that your code has a bug.