'final' variables

Walter Bright newshound at digitalmars.com
Tue Mar 20 12:04:49 PDT 2007


Lionello Lunesu wrote:
> I understand, but what's the point of telling the compiler "I don't want 
> to rebind this variable"? It doesn't seem like an optimization hint. 
> Like telling "func(const int i)" in C++ doesn't actually do anything. 
> You just type more.

Final is handy for a number of things:
1) For class members, it would indicate that a class is not mutable once 
it's constructed. Probably most classes are like this, and so it's a 
handy way to document it.
2) Andrei pointed out to me that one can often replace:
	auto x = initializer;
with:
	final x = initializer;
to indicate in a block of code that x will never be reassigned. This 
aids in understanding the code. It's a style I intend to adopt.
3) For cases like:
	const char[] s = "hello";
is it s that's not rebindable, or is the data that s is pointing to 
immutable? This never fails to confuse me (in C++), so I like to be able 
to say which it is in a clear manner.

> And if you later want to rebind 'i' you'll have to 
> change the interface. Lose-lose?

Although final is specified in the interface, it is not part of the 
interface. It only affects the implementation of the interface. You'll 
be able to change it without affecting any users of the interface.



More information about the Digitalmars-d mailing list