-
Notifications
You must be signed in to change notification settings - Fork 3
Extend and Traits
Hassium has a keyword called extend
that is used to extend the attributes of a class, both user defined and builtin. The syntax for an extended class is extend <classname> { <body> }
.
Let's take the builtin class Thread
, which exists in the global namespace:
extend Thread {
func weAddedThis () {
println ("This wasn't here before, but I added it anyway!");
}
}
Now in main
we can call:
func main () {
Thread.weAddedThis ();
}
Traits are a construct used to check if a class matches a certain blueprint or format. It is important to know that classes cannot be of the type trait, merely checked to see if they match it. The syntax for a trait is:
trait <name> { <name> : <type>, ... }
.
Let's create one to check to see if a class can preform additive methods. We'll call this trait addable
.
trait Addable {
add : func,
sub : func
}
This trait contains the blueprints for an attribute of type func
named add
and an attribute of type func
named sub. Now we can use the is
operator on two classes we make to check if they are addable.
class Calc {
func add () {}
func sub () {}
func mul () {}
func div () {}
}
class Multi {
func mul () {}
func div () {}
}
func main () {
println (Calc is addable); # prints true.
println (Multi is addable); # prints false.
}
Since the Calc
class contains a function named add
and a function named sub
, so it passes the test, Multi
does not contain both methods so it returns false
.