Constructors

Type constructors are special methods that allow initializing instances of the type. They are defined as a void method named construct with optional parameters. When you're using the new keyword, you're actually calling the appropriate constructor method.

type zomg
{
  int @a
  
  void construct
  {
    @a = 0
  }

  void construct: int value
  {
    @a = value
  }

  string to_s
  {
    return "<zomg @a=" + @a.to_s + ">"
  }
}

var obj = new zomg
var obj2 = new zomg 1337

println obj // "<zomg @a=0>"
println obj2 // "<zomg @a=1337>" 

If there are no constructors defined in a type, Mirelle will create a default constructor without parameters. If you have a parametrized constructor, however, the default one will not be created.

Constructors must be always marked as void and cannot return values.

Autoconstructor

Sometimes, when your type contains many fields, it may be bothersome to write a constructor with lots of parameters. Consider the following code:

type zomg
{
  var @field1 = 1
  var @field2 = 2
  var @field3 = 3
  var @field4 = 4
  var @field5 = 5

  void construct: int f1, int f2, int f3, int f4, int f5
  {
    @field1 = f1
    @field2 = f2
    @field3 = f3
    @field4 = f4
    @field5 = f5
  }
} 

Instead of all this horror, you can just write:

type zomg
{
  var @field1 = 1
  var @field2 = 2
  var @field3 = 3
  var @field4 = 4
  var @field5 = 5

  autoconstruct
} 

The constructor will be created automatically, requesting values in the same order as they're defined in the type. This way is significantly shorter and allows modifying the list of fields easier.

Last edited Mar 16, 2011 at 11:22 PM by impworks, version 1

Comments

No comments yet.