Search code examples
d

D Language Static Class Function Undefined Identifier


I started learning the D programming language(it's pretty awesome), and ran into a slight problem when I started to explore functions. The setup is pretty basic; it's just a way to figure out the similarities of the language to others that I have used. Here is my class declaration:

module TestClass;
import std.string;
class TestClass
{
    this()
    {
        // Constructor code
    }

    public static string getData(){
        return "Test";
    }
};

and here is my main:

module main;

import std.stdio;
import std.string;
import TestClass;

void main(string[] args)
{
    writeln(TestClass.getData());
    stdin.readln();
}

There seems to be an issue with calling the static function in TestClass. I get a "undefined identifier" error. Here is a picture:

enter image description here

Does anyone know what I am doing wrong? I tried looking through the documentation on the digital mars website, but to be honest it is a little counter-intuitive.


Solution

  • Not having a D compiler handy right now and not having worked with the language in a while, I think I remember having similar problems when starting out in D.

    I think the import statement pulls in the module TestClass, so when you type TestClass.getData(), the compiler thinks that you are referring to a global function getData in the TestClass module.

    You can fix this in several ways:

    • Rename the TestClass module to something else. This will avoid the name clash between the module and the class. As Jonathan M Davis notes in the comments, the convention in the D community is to use lowercase characters for modules, so you could simply rename it to testclass.
    • Import the class explicitly:

      import TestClass : TestClass;
      
    • Write TestClass.TestClass.getData() to refer to the class inside the module.

    It should also be pointed out that, unlike in Java, classes don't need to be each in a separate module in D.