Java like class importing

Alexandru Ermicioi alexandru.ermicioi at
Sun Nov 17 11:36:47 UTC 2019

On Sunday, 17 November 2019 at 09:03:03 UTC, tcak wrote:
> I started working on a project which contains many classes in 
> it. One of them is name "SpacePosition" which holds x and y 
> position, and a method "distance". Distance is defined as both 
> instance method and class method. So I can call it like,
> SpacePosition.distance( pos1, pos2 );
> After defining many classes in the my main.d file, I wanted to 
> separate the classes into separate files. I created a new file 
> with the name "SpacePosition.d" and put the class into it.
> In the main.d, I added the line "import SpacePosition;". And 
> when I compile the main.d, BAM!
> Error: undefined identifier distance in module SpacePosition
> So you have to import it like "import SpacePosition: 
> SpacePosition;" or call the method like 
> "SpacePosition.Spaceposition.distance( pos1, pos2 )".
> While the main purpose of modules/namespaces is to separate the 
> things so they can be managed much easily, this adds the code 
> weirdness.
> I think it would be better to add "import" mechanism a new 
> syntax to make calls as done in Java. Example:
> import class my.project.classes.SpacePosition;
> So the compiler would enforce SpacePosition.d file to contain a 
> single class definition with name "SpacePosition".

The problem was that module name was same as class name, and that 
got into conflict. Try make it lowercase then it should work. 
Also check for D code style, per 
it's recommendation module name should be all lowercase alpha 
numeric name if possible.

Regarding java like semantics for modules, I doubt it will be 
appropriate since unlike java, D modules repesents a collection 
of interdependent entities (classes, funcs etc.) which sometime 
need access to private state of each other similar to how class 
friends in c++ works, therefore it will be quite complicated to 
expose two classes that are interdependent (access private state 
of each other) if only one is allowed to be public.

Best regards,

More information about the Digitalmars-d mailing list