d equivilent of java's public static class fields

Jacob Carlborg doob at me.com
Mon Aug 9 01:30:02 PDT 2010


On 2010-08-08 21:12, %u 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.
>
> (There are other syntax errors in D code, I'm fixing them one by one)
>
> ######### Begin D code (ported from Java code below, and I probably should use
> an Enum, but .... haven't)
> public class Answer
> {
> /* I've tried various combinations of syntax here */
>    static int CORRECT = 0;
>    public const int WRONG = 1;
>
>    private int _answerCode;
>    private string _answerText;
>
>    /*
>    */
>    public this(int answerCode, string answerText)
>    {
>      _answerCode = answerCode;
>      _answerText = answerText;
>    }
>
>    /*
>    */
>    public int getAnswerCode()
>    {
>      return _answerCode;
>    }
>
>    /*
>    */
>    public string getAnswerText()
>    {
>      return _answerText;
>    }
> }
> ####### End D code code
>
> ####### Begin Java code (included to show how it was done in java)
> public class Answer
> {
>    public static final int CORRECT = 0;
>    public static final int WRONG = 1;
>
>    private int _answerCode;
>    private String _answerText;
>
>    /*
>    */
>    public Answer(int answerCode, String answerText)
>    {
>      _answerCode = answerCode;
>      _answerText = answerText;
>    }
>
>    /*
>    */
>    public int getAnswerCode()
>    {
>      return _answerCode;
>    }
>
>    /*
>    */
>    public String getAnswerText()
>    {
>      return _answerText;
>    }
> }
> ###### End Java code
>
> ######### Begin D code snippet trying to use the Answer class
> int asd = Answer.CORRECT;<-- compile error here
>
> try
> {
>    answer = problem.getAnswer(reply); // grade answer
>
>    if (answer.getAnswerCode() == Answer.CORRECT)<-- compile error here
>      inOut.displayAnswer("Correct");
>    else
>      inOut.displayAnswer("Nope, " ~ answer.getAnswerText());
> }
> catch (Exception iae)
> {
>    inOut.displayAnswer(iae.getMessage());
>    repeatQuestion = true; // show same question again
> }
> ######### End D code snippet

I don't know how you are trying to use your class but I don't see any 
errors in your code.

-- 
/Jacob Carlborg


More information about the Digitalmars-d-learn mailing list