Package functions cannot be abstract?!

Marco de Wild mdwild at sogyo.nl
Wed Jan 30 07:30:48 UTC 2019


On Wednesday, 30 January 2019 at 04:05:15 UTC, Jonathan Levi 
wrote:
> Why in the world can abstract functions not be only visible to 
> only a package?

If you could make a package-private function abstract, that would 
imply that implementations outside of the package are never 
functional.

In foo/x.d:
---
module foo.x;

public abstract class X {
     package abstract doThings();
}

public void letsDo(X x) {
     x.doThings();
}
---

In bar/y.d:
---
module bar.y;
import foo.x;

public class Y : X {
     // Does not know that doThings() needs to be implemented.
}

void demo() {
     letsDo(new Y());
}
---
This will give a runtime error, as y.do() is called without being 
implemented.

Depending on your exact problem, you could:
- Make X package private.
- Make doThings() protected.
- Make derived classes of X final.
- Expose methods publicly that take X as an input parameter.

I.e.:
module foo.x;

package abstract class X {
     protected abstract void doThings();
}

public class XImpl : X {
     protected override void doThings() {
         import std.stdio;
         writeln("Hello world");
     }
}

public void letsDo(X x) {
     x.doThings();
}
---

In bar/y.d:
---
module bar.y;
import foo.x;

void demo() {
     letsDo(new XImpl());
}
---


More information about the Digitalmars-d mailing list