Traits

A trait is a construct that lets you use code again and again. A typical trait is a set of methods that can become part of many different elements. Such elements include classes, structures, and other traits.

Traits have some of the same qualities as classes and structures, but there are important differences:

Declaration of traits

A trait usually starts with Trait and is completed with End Trait. Between these two lines you can put one or more permitted statements: Method, Property, Function, Sub, and TBD.

A class that uses a trait has access only to the public members of the trait—methods and properties. These also become part of the interface of the class . The class cannot directly get access to the other members of the trait.

A method or property is usually made with a body of statements. But if you use the modifier @Abstract, the method or property cannot have a body. A class that uses the trait must declare the method or property again, and supply a body of statements.

Multiple traits

TODO

Different methods with the same signature

When you mix traits into a class, that class can possibly have two methods with the same signature. Procedures with the same name and parameters cannot be in the same scope. Thus, the result is a compile-time error. But you can change the names of the methods to correct this error.

Trait A
    Method Calculate
        ' ...
    End Method
End Trait

Trait B
    Method Calculate
        ' ...
    End Method
End Trait

Class Calculator Does A, B
    Method CalculateA Does A.Calculate
    Method CalculateB Does B.Calculate
End Class

Changing method visibility

Trait Foobar
    Method Foo
        ' ...
    End Method
    Method Bar
        ' ...
    End Method
End Trait

Class Barless Does Foobar
    Function Bar Does Foobar.Bar
End Class

Traits made from traits

Trait Foo
    Method Foo
        ' ...
    End Method
End Trait

Trait Bar
    Method Bar
        ' ...
    End Method
End Trait

Trait Foobar Does Foo, Bar
    ' ...
End Trait

Abstract traits

If all of the methods and properties of a trait must be abstract, you can put the modifier @Abstract before the trait. Then it is not necessary to put the modifier before each method and property.

An abstract trait has more limits than a usual trait:

Shared trait members

TODO

Properties

TODO

Uses for traits

TODO

Examples

@Abstract Class Pet
End Class

Trait Walk
    Method StartWalking
    End Method
End Trait

Trait Swim
    Method StartSwimming
    End Method
End Trait

@Abstract Trait Speak
    Method Speak As String
End Trait

Class Dog Is Pet Does Walk, Swim, Speak
    @Override Method Speak As String
        Return "Arf"
    End Method
End Class

Class Cat Is Pet Does Walk, Speak
    @Override Method Speak As String
        Return "Meow"
    End Method
End Class

Class Fish Is Pet Does Swim
End Class

See also