Default argument values
bearophileHUGS at lycos.com
Thu May 20 13:56:08 PDT 2010
This page talks about default function argument values in C#4:
Near the end it says:
>If we change the value of the optional argument from 0 to 1, we have to recompile all calling code for the calling code to get the updated value! For folks shipping assemblies for a living, this means that optional argument values don't version well, as callers have to recompile. When I used to work for a company whose product included a DLL, we avoided optional method arguments for just this reason. It's not a reason not to use optional arguments, but it's important to understand how they work so that you don't run into headaches later.<
D too copies the default value at the calling point. Looking at this from the eyes of a Python programmer this looks like a dirty hack.
This can be a cause of problems in D dlls too, I am not sure.
The related discussion on Reddit:
Someone has given this answer:
>Have you looked at Scala's implementation on the JVM? It's very simple. Each default parameter generates a static method with a predictable name (e.g. foo$default$3 for parameter 3 of method foo) that may be called to compute the default value of an unsupplied parameter. With this approach, changing the default value of an existing default-valued parameter means changing the implementation of a static method without changing its signature, so there is no need for callers to be recompiled. Because of JIT inlining, the performance should be the same as C#'s earlier-bound approach.<
You can find more info about this Scala feature here:
I copy here how it's implemented:
For every parameter with a default argument, a synthetic method which computes the default expression is generated. When a method application uses default arguments, the missing parameters are added to the argument list as calls to the corresponding synthetic methods.
def f(a: Int = 1, b: String)
// generates a method: def f$default$1 = 1
f(b = "3")
// transformed to: f(b = "3", a = f$default$1)
A default argument may be an arbitrary expression. Since the scope of a parameter extends over all subsequent parameter lists (and the method body), default expressions can depend on parameters of preceding parameter lists (but not on other parameters in the same parameter list). Note that when using a default value which depends on earlier parameters, the actual arguments are used, not the default arguments.
More information about the Digitalmars-d