Home > Enterprise >  Rascal MPL overload library functions
Rascal MPL overload library functions

Time:12-12

It's easy to overload your own functions like so:

void testVal(loc l) {
    println("LOC <l>");
}

void testVal(value v) {
    println("VAL <v>");
}

such that testVal(|tmp:///|) will call the first method. I wish to do the same to IO::println:

void println(loc l) {
    IO::println("my custom println function");
}

to serve for debug purposes. println(|tmp:///|) should now print "my custom println function". Is it possible to do this? For me this code still defaults to the IO implementation.

CodePudding user response:

Function overloading works by non-deterministic selection. So if the patterns of testVal or println overlap, then there is no way to know which one is chosen first.

In fact in your example, loc l overlaps with value v so the priority between the two alternatives is undefined.

To fix this, one of the alternatives must get a more precise pattern (e.g. change value v to num v to distinguish it from loc l, or you can put the default modifier before the function:

default void testVal(value v) {
   println("VAL <v>");
}

If you want to override an existing function that does not have the default modifier, I am afraid you are out of luck. You can't change the IO module to add the default. So to work around this issue you can wrap the IO::println function in your own function:

default void pln(value... v) {
   println(v);
}

void pln(loc l) {
   println("LOC <l>");
}
  • Related