0

i have query that is it fine to use to use named parameter which having name parameter and the variable name same in a function call

for example

fun fun1( to:string ){
//body}

fun fun2( ){
to = "xyz"
fun1( to = to)
}

calling fun1 which have a parameter name "to" and passing variable "to" is it okay to do so . In either of case can someone also explain how the compiler will resolve this

2
  • "is it okay to do so" What do you mean by "okay"?
    – Sweeper
    Commented Jan 20 at 9:16
  • 1
    Outside of formatting and naming mistakes, what you're asking is valid Kotlin and behaves where the value of to in fun2 gets "xyz". I assume you're coming from a C background or a language that lets you do assignment in a function argument. You can't do assignment in a function argument in Kotlin (try it) so there's no ambiguity.
    – possum
    Commented Jan 20 at 10:20

1 Answer 1

1

In Kotlin, property or variable assignment can only happen if the variable/property name and = are at the beginning of a line of code (or the first code in the scope { } of a lambda or defined function), not in the middle of an expression or list of function arguments.

Since the compiler sees to = inside the argument list of a function call, it resolves it as a named argument rather than a variable assignment, so the to of to = is interpreted as a function parameter name.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.