tech

[English] [Japanese]

15. Class advertise

LuneScript allows transparent access to methods of members held by classes.

advertise

I think the expression "transparent access" is difficult to convey, so I will explain it with the following example.

// @lnsFront: ok
abstract class Test {
   pub abstract fn foo(): str;
   pub abstract fn bar(): str;
}
class TestSub1 extend Test {
   pub override fn foo(): str {
      return "foo";
   }
   pub override fn bar(): str {
      return "bar";
   }
}
class TestSub2 extend Test {
   pri let sub:TestSub1;
   advertise sub;
   pub override fn bar(): str {
      return "hoge" .. self.sub.bar();
   }
}
fn func( test:Test ){
   print( test.foo(), test.bar() );
}
func( new TestSub1() ); // foo, bar
func( new TestSub2( new TestSub1() ) ); // foo, hogebar

TestSub2 advertises member sub.

This causes TestSub2 to internally generate a call to the member sub's method (foo,bar) like this:

// @lnsFront: skip
pub override fn TestSub2.foo(): str {
   return self.sub.foo();
}
pub override fn TestSub2.bar(): str {
   return self.sub.bar();
}

TestSub2 in this example declares the method bar().

If the method declared in this way and the method generated by advertise have the same name, the declared method takes precedence.

Note

When you advertise multiple members, the behavior is undefined if there are methods with the same name among those members.

summary

  • By declaring advertise, member methods can be accessed transparently
  • Be careful when advertising multiple members

Next time, I will explain the interface.