Wiki

Type Extensions

Extend an existing type with additional method(s).

Grammar

extend EXISTINGTYPE
   def ADDMETHOD
       ...
   ....

Example

extend String

    def doubleLength as int
        return .length * 2

    def capitalized as String
    """
    Returns the string with the first character capitalized.
    Returns a blank string for a blank string.
    """
    ensure
        result.length == .length
        result.length implies result[0] == result[0].toUpper
    test
        assert 'chuck'.capitalized == 'Chuck'
        assert 'Chuck'.capitalized == 'Chuck'
        assert ''.capitalized == ''
        assert ' foo'.capitalized == ' foo'
        assert 'f'.capitalized == 'F'
        assert '1aoeu'.capitalized == '1aoeu'
    body
        if .length == 0, return this
        return this[:1].toUpper + this[1:]

Restrictions

You can use extension methods to extend a class or interface, but cannot override existing matching methods.

See also: StandardLibraryExtensionMethods, LanguageTopics