Traits are akin to interfaces in Java and Kotlin: they allow you to define a list of common functions and variables that can be implemented on multiple types, thus promoting code reuse. They are declared similar to classes(#8), but with the trait keyword instead, and added to a class using the has keyword in the class header:
trait Foo {
}
class Bar has Foo {
}
Traits can also have functions and variables declared in them. Functions do not need to have a body and variables do not need to have a declared value;
trait Foo {
var x : Int;
var y : Int = 1;
func doXThing();
func doYThing() {
print("Hey!");
}
}
Overview
Traits are akin to interfaces in Java and Kotlin: they allow you to define a list of common functions and variables that can be implemented on multiple types, thus promoting code reuse. They are declared similar to classes(#8), but with the
trait
keyword instead, and added to a class using thehas
keyword in the class header:Traits can also have functions and variables declared in them. Functions do not need to have a body and variables do not need to have a declared value;