Chapter 11. Traits and Enums
In Hassium, a trait
is a construct that defines a template that classes compare to. An enum
is a set of named values that each represent an integer. This chapter will go over the declaration and comparison of a trait
, as well as the declaration and usage of an enum
.
11.1 - Traits
A trait
contains a listing of names and types that represent the required attributes of the classes they will compare to. A trait
must be declared in a class-level or global scope. The declared trait
compares with a class using the is
operator.
The following is a program that defines two classes and a trait
. The main
method checks each class to see if it implements the trait
.
trait Calculable {
add : func,
sub : func,
mul : func,
div : func,
SpecialClass : class
}
class ClassOne {
func add (x, y) { return x + y; }
func somethingelse () {}
}
class ClassTwo {
class SpecialClass { }
func add (x, y) { return x + y; }
func sub (x, y) { return x - y; }
func mul (x, y) { return x * y; }
func div (x, y) { return x / y; }
func somethingelse () {}
}
func main () {
printf ("ClassOne is Calculable: {0}\n", ClassOne is Calculable);
printf ("ClassTwo is Calculable: {0}\n", ClassTwo is Calculable);
}
Output:
false
true
The first line of main
checks ClassOne
against the requirements of Calculable
. ClassOne
contains a func
add
but contains no func
sub
, so the result of is
is false
. The second line of main
checks ClassTwo
against the requirements of Calculable
. ClassTwo
contains a func
add
, func
sub
, func
mul
, func
div
, and a class
SpecialClass
, so the is
operator returns true
.
11.2 - Enums
An enum
contains a list of elements which each represent a number in ascending order. This is useful primarily for protocol design where it can be confusing to check data against constant values.
Let's create a simple enum
that will represent the opcodes of some common mathematical operations.
enum OpCode {
add,
sub,
mul,
div
}
func main () {
println (OpCode.add);
println (OpCode.div);
}
Output:
0
3
Due to the order in which the elements are declared, OpCode.add
represents 0
and OpCode.div
represents 3
.
You can optionally manually assign the values to an enum
.
enum OpCode {
# this might be used for something later
add = 1,
sub = 2,
# some more filler space
mul = 4,
div = 5
}
func main () {
println (OpCode.add);
println (OpCode.div);
}
Output:
1
5
Chapter 11 - Exercises
Exercise 11.1
Create a trait
named Convertable
which checks if a class
contains the tobool
, tochar
, tofloat
, toint
, and tostring
functions. Test it on two classes that do not implement this trait
and one that does.
Exercise 11.2
Create an enum
named ID
. Have four elements in this enum
auto-assign their values and directly assign values to two other elements.