ceylon
ceylon copied to clipboard
Add way to define named-only parameters
I’ve been thinking for a while that some parameters of functions should only ever be passed using named arguments, to avoid confusion (my go-to example is assertEquals so you don’t have to remember the order of expected and actual, though that might be controversial), and whether there might be a way to enforce that.
Today I found out that Python has something like this, which motivated me to file this issue. It looks like this:
def compare(a, b, *, key=None):
# ...
Any parameters after the bare asterisk cannot be passed as positional arguments – a TypeErrror is raised if you attempt to do so.
However, I don’t think that’s a very Ceylonic style, and I also find it very unreadable unless you already know the syntax. For Ceylon, I think an annotation would make much more sense:
function compare(Object a, Object b, named String? key = null) {
// ...
}
Furthermore, since unlike Python we have a separate compilation step, I would make this a (suppressible) warning instead of a hard error. (In Python, the only alternative would be delegating this check to an external tool, which most people would never run.)
Specifying non-named parameters after named ones should probably be a warning as well.
I would prefer named annotation for parameters to indicate this.
It could also improve DSLs for building HTML/XML content -- if attributes would always be required to be called with named argument syntax, it would make the declarations look so much more closed to the markup language convention...