Some code examples

Reiner Pope reiner.pope at gmail.com
Thu Jul 27 14:04:35 PDT 2006


class Cell
{   int _value;
     assignable int _hashCode;

     public int hashCode() readonly
     {   if (hashCode == 0)
             hashCode = ...
         return hasCode;
     }

     public int value() readonly
     {   return _value;
     }

     public int value(int newValue)
     {   return (_value = newValue);
     }

     final char[] _filename;
     readonly char[] _filename2;
     final readonly char[] _filename3;

     public void foo()
     {   _filename = something; // Error, _filename is final
         _filename[0] = 'c'; // Legal
         _filename2 = something; // Legal
         _filename2[0] = 'c'; // Error, _filename2 is readonly
         _filename3 = something; // Error
         _filename3[0] = something; // Error
     }

     public void foo() readonly // We can overload by immutability
     {   _filename = something; // Error, _filename is final
         _filename[0] = 'c'; // Error, _filename is this-mutable and 
enclosing function, foo() is readonly
         _filename2 = something; // Error, enclosing function is 
readonly and _filename2 isn't mutable, but this-mutable
         _filename2[0] = 'c'; // Error, _filename2 is readonly
         _filename3 = something; // Error
         _filename3[0] = something; // Error
     }

     public void bar() rotemplate
     {   foo(); // If this is readonly, call the readonly version, else 
call the non-readonly version
     }

     public void baz() readonly
     {
     }

     public void bam()
     {   baz(); // Error, baz is readonly
     }
}

rocheck char[] toupper(rocheck char[] string)
{   foreach (char c; string)
     {   if (needsToModify())
         {   char[] modifiable = string.ensureWritable();
             modifyIt(modifiable);
             return modifiable;
         }
         return string;
     }
}

void main()
{   readonly char[] h = "hello world";
     char[] h2 = "hello world";
     readonly char[] h3 = "HELLO WORLD";
     char[] h4 = "HELLO WORLD";
     readonly something = toupper(h); // A copy is made, since h is readonly
     readonly something = toupper(h2); // No copy is made, since h2 is 
modifiable
     readonly something = toupper(cast(readonly)h2); // A copy is made, 
since we requested it
     readonly something = toupper(h3); // No copy is made, and the 
return value can't be modified
     char[] h5 = touppper(h2); // Illegal: rocheck can't be converted to 
mutable
     char[] h6 = toupper(h2).ensureWritable(); // Legal, and all dups 
are avoided. Great!
     readonly something = toupper(h4); // Legal, and no copy is made
}


That's enough examples. It only covers a few cases, but it's all I'm 
doing for now.



More information about the Digitalmars-d mailing list