Interested in D, spec confuses me.

H. S. Teoh via Digitalmars-d digitalmars-d at puremagic.com
Tue Feb 2 12:15:15 PST 2016


On Tue, Feb 02, 2016 at 07:50:57PM +0000, Bambi via Digitalmars-d wrote:
> On Tuesday, 2 February 2016 at 15:48:02 UTC, anonymous wrote:
> >"immutable" is not a homonym here. It means the same thing ("cannot
> >ever change"). And it's not redundant either, as the two instances
> >apply to different targets. It's clear what the first "immutable"
> >ties to: It qualifies the return type. The second one is less clear:
> >It qualifies the type of the object, meaning the method can only be
> >called on an immutable object.
> >
> >Leaving either of them out changes the meaning of the signature:
> >`int[] bar() immutable {}` - Return type is mutable now.
> >`immutable(int[]) bar() {}` - Object type is mutable now. I.e., this
> >method can be called on a mutable object, and it cannot be called on
> >an immutable object.
> 
> Making the return value immutable is a very different thing from
> making every value of the object immutable to the method alone. These
> are different meanings. It reads like a redundancy but has different
> meanings. This isn't good in my eyes.
[...]

It's an unfortunate historical accident that function attributes can
easily be conflated with return type attributes. Different people have
pushed for prohibiting (apparently) ambiguous cases, but so far Walter
has been resistant to the idea. Because of this, my own recommendation
is to always use parenthesis when writing type qualifiers, and always
write function attributes on the right rather than on the left:

	struct S {
		// Do write:
		immutable(int) func() { ... }
		int func() immutable { ... }
		immutable(int) func() immutable { ... }

		// Don't write:
		immutable int func() { ... }
		immutable immutable int func() { ... } // may not compile
	}

I'd even recommend using parenthesis in variable declarations, just for
consistency's sake:

	// Do write:
	immutable(int) x;

	// Don't write:
	immutable int x;

Even though the two are identical, I think it's better to always write
parentheses so that you get into the habit of thinking of the type in
terms of parentheses, and don't get confused when you encounter
ambiguous cases (or at least you'll be on the alert when parentheses are
absent, and be sure read the function signature more carefully).


T

-- 
Debian GNU/Linux: Cray on your desktop.


More information about the Digitalmars-d mailing list