Why declare a function argument to be final?

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.

Leave a Comment