Type Extension
Cangjie supports type extensions, which allow users to add member functions to a type without changing the original type definition code. Specifically, Cangjie can extend a type by:
- Adding a function
- Adding an attribute
- Adding an overloaded operator
- Implementing an interface
In the following example, the printSize
member function is added to the String
type. Therefore, the printSize
function can be called in the same way as calling other predefined member functions.
extend String {
func printSize() {
print(this.size)
}
}
"123".printSize() // 3
When extensions and interfaces are used together, the language expression capability can be greatly improved. We can even add a new inheritance system to a type.
In the following example, a new interface Integer
is defined, and then extend
is used to implement the Integer interface for the existing integer types. In this way, the existing integer types become the subtypes of Integer. The sealed
modifier indicates that the interface can be implemented (or extended) only in the current package.
sealed interface Integer {}
extend Int8 <: Integer {}
extend Int16 <: Integer {}
extend Int32 <: Integer {}
extend Int64 <: Integer {}
let a: Integer = 123 // ok