madneon
madneon

Reputation: 537

Mark Haxe Class for forced extend?

Is there a compiler meta for Class declaration, that prevents creating Class instance before extending it? In other words - some sort of opposite of @:final meta.

Like so (last line of code):

class A {
    // ...
}

class B extends A {
    // ...
}

// ...
var b = new B(); // OK
var a = new A(); // induce compiler-error

Upvotes: 3

Views: 254

Answers (3)

Jeff Ward
Jeff Ward

Reputation: 19026

Both the other answers are correct (no constructor or private constructor), but there are a few more details that you may interest you:

  • Here's an example of no constructor. Of note is that A simply doesn't have a constructor, and B simply doesn't call super(). Other than that, everything else works as you'd expect.
  • Here's an example of a private constructor. You still can't instantiate a new A(), but you do still need to call super() from B's constructor.

Technicalities:

  • Use of some features (like a default value on a member variable) will cause A to get an implicit constructor, automatically. Don't worry, this doesn't affect constructability or whether you need to call super(). But know that it is there, and if necessary an implicit super() call is prepended to B's constructor. See the JS output to verify this.
  • In any case, know that you can still instantiate an A at runtime with var a = Type.createInstance(A,[]); as compile-time type checks do not limit RTTI.

Related discussion:

Aside from private/no constructor, Haxe doesn't have a formal notion of abstract classes1 (base classes not expected to be instantiated) or abstract methods2 (functions on abstract base classes with no implementation that must be implemented by a derived class.) However, Andy Li wrote a macro for enforcing some of those concepts if you use them. Such a macro can detect violations of these rules and throw compile-time errors.


1. Not to be confused with Haxe abstracts types, which are an entirely different topic.

2. Not to be confused with virtual functions, which wikipedia describes as a function which can be overridden (though various docs for various languages describe this highly loaded term differently.)

Upvotes: 2

KevinResoL
KevinResoL

Reputation: 982

Simply don't declare a constructor at all for class A

Upvotes: 6

madneon
madneon

Reputation: 537

One way of achieving this is to create private Class constructor:

class A {
    private function new() {
        // ...
    }
}

// ...
var a = new A(); // Error: Cannot access private constructor

Upvotes: 1

Related Questions