Skip to content

Instantly share code, notes, and snippets.

@wilkie
Created May 16, 2012 07:51
Show Gist options
  • Save wilkie/2708464 to your computer and use it in GitHub Desktop.
Save wilkie/2708464 to your computer and use it in GitHub Desktop.
Some weird obscure D syntax.
/+
Inner classes contain a hidden field that contains a reference to the
instance of the outer class. D has a special 'new' expression that can
be used to create instances of inner classes and attach them to outer
class instances.
+/
// Using printf
extern(C) int printf(char*, ...);
// Class A has a public inner class B
class A {
// Class A has an instance variable 'x'
int x;
// A constructor that sets 'x'
this(int bar) {
x = bar;
}
// Inner class B
class B{
void foo() {
printf("hello %d\n", x);
}
}
}
int main(char[][] args) {
// Creating a new instance of A
auto a1 = new A(42);
auto a2 = new A(10);
// Creating a new instance of B within the context of 'a'
auto b1 = a1.new B;
auto b2 = a2.new B;
// Sweet
b1.foo();
b2.foo();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment