Extending Existing Types

Objective: Add methods to the integer type.

Python

Extending built-in class is not possible. Inharitance helps to workaround the problem.

class Int(int):
    
    @property
    def dots(self):
        return '.' * self

x = Int(9)

# Method used as a property, so parentheses not needed.
print(x.dots)

Rust

Extending built-in types is possible, but how to do it for all integer types at once?

trait Dots {
    fn dots(&self) -> String;
}

impl Dots for i32 {
    fn dots(&self) -> String {
        ".".repeat(*self as usize)
    }
}

fn main() {
    // There are no properties, we need parentheses.
    println!("{}", 9.dots());
}

Crystal

Inheritance is available, but not easy in case of this example. Instead of that, method can be added to the existing type:

struct Int
  def dots
    "." * self
  end
end

# Method can be called with or without parentheses.
puts 9.dots