1

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.

1 Answer 1

1

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>");
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! What's the value... v notation? Is it some sort of unpacking?
O that's "varargs" like in C and Java, it means list[value] v but you don't have to put the square brackets when calling the function: pln(1, 2, 3)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.