Grok Namespaces - vilinski/nemerle GitHub Wiki

This page is a part of the Grokking Nemerle tutorial.

Namespaces

Classes and modules can be put in namespaces. Namespaces at the conceptual level prepend a string to names of objects defined within them.

 namespace Deep.Thought
 {
   class Answer
   {
     public static Get () : int
     {
       42
     }
   }
 }

 namespace Loonquawl
 {
   class Brain
   {
     public static Run () : void
     {
       System.Console.WriteLine ("The answer {0}",
                                 Deep.Thought.Answer.Get ())
     }
   }
 }

As you can see, the name of the Get function is first prepended with the name of the module (Answer) and then with the current namespace (Deep.Thought), forming its full name: Deep.Thought.Answer.Get.

Another example is the WriteLine method of the Console module, defined in the System namespace.

Making long names short

In order not to write System.Console.WriteLine or Deep.Thought.Answer.Get all the time you can import all declarations from the specified namespace into the current scope with the using directive.

Thus the Loonquawl.Brain module from the example above could be:

 namespace LoonquawlUsing
 {
   using System.Console;
   using Deep.Thought.Answer;

   class Brain
   {
     public static Run () : void
     {
       WriteLine ("The answer is {0}", Get ())
     }
   }
 }

While we see not much gain from the using directive in this example, it can be handy when you use the WriteLine method 100 times, and/or your classes are in Some.Very.Long.Namespaces.

Note that unlike in C# all methods of a class can be imported into the current namespace. Thus, using is not limited to namespaces, but it also works for classes. The new thing is also the fact, that currently opened namespaces are used as prefix in all type lookups - for example if there is using System;, then you can write Xml.XmlDocument (), or with an additional using System.Xml; you can write XmlDocument (). Neither of these is possible in C#.

It is also possible to create (shorter) aliases for namespaces and types. It is sometimes useful in case when two namespaces share several types, so they cannot be imported with using simultaneously. This works in similar way to C#.

 namespace LoonquawlAlias
 {
   using SC = System.Console;
   using DTA = Deep.Thought.Answer;

   class Brain
   {
     public static Run () : void
     {
       SC.WriteLine ("The answer is {0}", DTA.Get ())
     }
   }
 }
⚠️ **GitHub.com Fallback** ⚠️