d equivilent of java's public static class fields

Simen kjaeraas simen.kjaras at gmail.com
Sun Aug 8 12:28:35 PDT 2010


%u <throwaway at limewall.org> wrote:

> I'm porting some code from Java to D and am getting stuck on what Java  
> calls
> static class fields.  I can't find out how to write the functional (or  
> best
> practices) equivalent in D.
[snip]
>   static int CORRECT = 0;
[snip]
> int asd = Answer.CORRECT; <-- compile error here
[snip]
>   if (answer.getAnswerCode() == Answer.CORRECT) <-- compile error here

The default access level in D is private, so CORRECT will not be
available outside the module in which Answer is defined.

As you mention, you should probably use an enum for wrong/correct.
However, due to lookup rules, an embedded enum would require users to
specify Answer.Correctness.CORRECT/WRONG, so separate enums for each
might be a better idea.

The most common way to expose the stored values in D code would probably
be as properties:

class Answer {
     alias int Correctness;
     enum Correctness CORRECT = 0;
     enum Correctness WRONG = 1;

     Correctness _answerCode;
     string _answerText;

     @property Correctness answerCode( ) const {
         return _answerCode;
     }

     @property string answerText( ) const {
         return _answerText;
     }
}

-- 
Simen


More information about the Digitalmars-d-learn mailing list