E4073

E4073#

Cannot provide default implementation for traits from other packages.

This is a corollary of the orphan rules of traits and types in MoonBit. Default implementation can be seen as implementing the trait for all possible types, including types defined within or outside of current package. Therefore, it is only possible for default implementation to be defined in the package of the trait, otherwise it would violate the orphan rules.

Erroneous example#

Suppose you have a trait T defined in package a in module username/hello:

a/a.mbt:

// We need the trait to be pub(open) so that it can be implemented from outside.
pub(open) trait T {
  f(Self) -> Int
}

And when you want to define a default implementation for the trait in another package, say b:

b/moon.pkg.json:

{
  "import": [
    "username/hello/a"
  ]
}

b/b.mbt:

impl @a.T with f(self : Self) -> Int {
  //           ^
  // Error: Cannot provide default implementation for trait @a.T from package a
  ignore(self)
  0
}

Suggestion#

To fix this error, you can move the definition of the trait and the default implementation of this trait into the same package. Say you can move the trait definition into package b:

b/b.mbt:

pub(open) trait T {
  f(Self) -> Int
}

impl T with f(self : Self) -> Int {
  ignore(self)
  0
}