Matthew Molloy
Matthew Molloy

Reputation: 1186

Haxe java.lang.Object Equivalent

Haxe allows class inheritance hierarchies

class Honda extends Car {
...
}

is there a common inheritance hierarchy root for all objects? I have a generic container class that could contain any object and I want to be able to declare

var _contents:Object; //Any class instance in _contents

How can I do this?

Upvotes: 0

Views: 133

Answers (2)

clemos
clemos

Reputation: 426

You can also use {} as a type, which will accept class instances as well as anonymous objects :

var _contents:{};

We also have Dynamic, which basically means "anything" (not only objects, but also primitives like Bool, Int, etc).

If your class is a generic container, you may want to type its content, though, using type parameters:

class Container<T> {
  var _contents:T;
  public function new(contents:T):Void {
    _contents = contents;
  }
}

And then:

var arrayContainer = new Container([]);
var stuffContainer = new Container({foo:"bar"});
var classContainer = new Container( new Stuff() );

Upvotes: 6

Quip Yowert
Quip Yowert

Reputation: 444

The inheritance root for classes is Class<T> so the following should work:

var _contents:Class<T>;

However, to store an Enum, you would have to use Enum<T> instead.

From the manual:

There is a special type in Haxe which is compatible with all classes:

Define: Class<T>

This type is compatible with all class types which means that all classes (not their instances) can be assigned to it. At compile-time, Class<T> is the common base type of all class types. However, this relation is not reflected in generated code.

This type is useful when an API requires a value to be a class, but not a specific one. This applies to several methods of the Haxe reflection API.

Upvotes: 1

Related Questions