Constructor/Destructor
Constructor
The constructor syntax in THP is inspired by Kotlin.
Constructors are declared like function definitions:
// |this is the constructor |
class Animal(String fullname, Int age)
// Creating an instance
val cat = Animal("Michi", 3)
thp
A constructor declared that way is public.
Note that the parameters in the constructor (fullname
,
age
above) are not properties, and cannot be used
inside the class methods, only in the
init
block and properties declaration.
To declare properties in the constructor see Constructor promotion.
Constructor visibility
If you want to declare a constructor as protected
or private you need to add the constructor
keyword, after the visibility modifier:
// Cow has a protected constructor
class Cow
protected constructor(String color)
// Bat has a private constructor
class Bat
private constructor(Int height)
thp
Init block
The init
block allow us to run code during the
construction of the instance:
class Dog(String name)
{
pub String name = name
Int name_len = name.length
init
{
print("Dog created: {name}")
}
}
thp
Constructor promotion
Constructor parameters can serve as class properties.
This is done by adding a modifier and var
/val
.
class Parrot(
// A public property
pub val String name,
// A protected property
protected var Int age,
// A private property
var String last_name,
)
thp
By using this syntax you are declaring properties and assigning them at the same time.
The contructor parameters can also have default values.
Derived properties
You can declare properties whose values depend on values on the constructor.
class Animal(
val String fullname,
)
{
// A property whose value depends on `fullname`
// This is executed after the contructor
pub val Int name_length = fullname.length
}
val a2 = Animal("Doa")
print(a2.name_length) //: 3
thp
Constructor that may fail
TBD
Proposal 1:
class PrayingMantis(String name) -> self!Error
thp
Proposal 2:
class PrayingMantis(String name)
throws Error
thp
Proposal 3:
class PrayingMantis(String name)
{
init -> self!Error
{
// Something that may fail
}
}
thp
Destructor
The destructor in THP is the same as PHP.
class Owl
{
pub fun __destruct()
{
// Cleanup
print("Destroying Owl...")
}
}
thp