MoonBit Language Tour MoonBit

Local Methods

In previous lessons you learned how to define methods for types. Those methods must be defined in the same package as the type itself, the restriction applies only to public methods (method marked with pub).

Sometimes you may want to extend a type from another package with additional behavior. MoonBit allows you to add local (non-pub) methods for any type. These methods are visible only within the defining package, so different packages can safely add their own internal helpers to the same type without conflicts.

///|
/// Extend the `@sorted_set.SortedSet` type with local method `add_range`.
/// 
/// The `SortedSet` are defiend in `moonbitlang/core/sorted_set`, you can find 
/// the API docs in https://mooncakes.io/docs/moonbitlang/core/sorted_set
fn @sorted_set.SortedSet::add_range(self : Self[Int], l : Int, r : Int) -> Unit {
  for i in l..=r {
    self.add(i)
  }
}

///|
fn main {
  let set = @sorted_set.new()
  set.add_range(1, 10)
  set.add_range(15, 20)
  println(set)
}