E4061

E4061#

Cannot define method of foreign trait for foreign type.

Foreign here means that the type or trait is not defined in the current package. MoonBit follows the orphan rule, which means that you can only:

特征

类型

Allowed?

Native

Native

Yes

Foreign

Native

Yes

Native

Foreign

Yes

Foreign

Foreign

No

See the Access control of methods and trait implementations section of the MoonBit documentation for more information.

错误示例#

Suppose you have type A and trait B defined in package a in module username/hello:

a/a.mbt:

pub(all) type A Int
pub(open) trait B {
  to_int(Self) -> Int
}

a/moon.pkg.json:

{}

Now, if you want to implement trait @a.B for type @a.A:

b/moon.pkg.json:

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

b/b.mbt:

impl @a.B for @a.A with to_int(self : @a.A) -> Int {
  //                    ^~~~~~
  // Error: Cannot define method to_int of foreign trait @a.B for foreign type @a.A
  self._
}

MoonBit will report an error.

建议#

You can move either the trait or type into the current package where the implementation is in. If that is not possible, you can create a new type over the foreign type and implement the trait for the new type:

b/b.mbt:

type WrapA @a.A

impl @a.B for WrapA with to_int(self : WrapA) -> Int {
  ...
}