Assume named arguments for functions with default parameters


#1

So, not sure how this one would play out, just a thought though. Say (for example) I have this function:

fun Connection.executeUpdate(processAction: (Any) -> Any = {}, sql: String = "SELECT * FROM table;"): Connection{
     return executeSQL(SQL::executeUpdate, processAction, sql)
}

[Yes, I’m aware that a query would be used for the “SELECT”, this is just an example]

I want to be able to (if necessary) perform a function when I call it, but at the same time, I don’t think it will happen that often, so I give it a default parameter of an empty function. Now, these are two totally different Types, one is a function, with a parameter, that has a return value, the other is a String. Right now I can call this function (and utilize the default parameter) by calling:

connection.executeUpdate(sql = "INSERT INTO table...")

While that’s all fine and dandy, it doesn’t actually save me any time.

connection.executeUpdate({}, "INSERT INTO table...")

It would be really great if when dealing with parameters of different types, the kotlin compiler would infer the named argument. So if I have a function and a string, both with the function having a default value, and all I pass is a string, the compiler would automatically understand that I was assigning it to the only option I have.

Or, even further, let’s say I had a function parameter with a default, and two Strings, only one of which has a default value. If I only give one string to that function I would like the compiler to realize that I only have one string that doesn’t have a default value, so it needs to be assigned one, and the other one needs to use it’s default since I didn’t assign it one.

Now obviously, this wouldn’t be expected to work for every function, for example, let’s say I had a function parameter with a default, and two Strings, each with a default value, of course in that instance you’d need the compiler to say “hey, you only provided me with one option, this has two possible String types”.

This doesn’t apply to just functions and Strings obviously. This could apply to a function with an Int and a Boolean, or an Int and a String, or really, any parameters.


#2

This would complicate overload resolution significantly, so I think it’s very unlikely that such thing will ever be implemented.

Note, that in this particular case you could swap parameters of executeUpdate and then be able to call it in these forms:

    connection.executeUpdate("query") { ... }
    connection.executeUpdate("query")
    connection.executeUpdate { ... }

#3

Hmm. That’s what I sort of expected. Oh well, thanks for the alternative!