2

I'm trying to reuse function parameters some thing like this

fun test(i: Int) {
    i += 5
}

but as noted in this distinction

Function parameters are val not var

humazed
  • 74,687
  • 32
  • 99
  • 138
  • Really, it's typically considered bad practice to modify arguments. I'd create a new variable with a different name, assign it to the parameter, then use it. Also, can you declare the parameter as a `var`? – Carcigenicate Aug 02 '17 at 15:32
  • 1
    @Carcigenicate You can't designate function parameters as val/var in Kotlin.They are implied to be `val`. – Todd Aug 02 '17 at 15:36
  • why it is considered a bad practice I don't want to change the parameter in the outer scope just to avoid assign it. I think assign is more confusing, – humazed Aug 02 '17 at 15:41

2 Answers2

4

In Kotlin, function arguments are treated as val. That means you'll have to do something inside your function in order to "modifty" its reference.

Your solution will work, but I feel that it's a bad practice to shadow variables. It leads to confusion, and doesn't quite accurately cover the intent that you understand that the effect is local to the function.

I would go with something like this:

fun test(i: Int) {
    var i2 = i
    i2 += 3 // etc...
}
Todd
  • 30,472
  • 11
  • 81
  • 89
  • I have considered it, but in my case, the parameter names are width and height. and I feel renaming it would lead to less readable code. – humazed Aug 02 '17 at 15:43
0

the only solution I found is to use name shadowing i.e something like that

fun test(i: Int) {
    var i = i
    i += 5
}

I'm not sure if it the best solution because it doesn't feel right, even IntelliJ IDEA warns me about it.

I was hoping for thing magical like

fun test(var i: Int) {
    i += 5
}

but unfortuantly this doesn't even comile.

humazed
  • 74,687
  • 32
  • 99
  • 138
  • 1
    that's interesting Kotlin can define variables with duplicated parameter name. maybe it is a bug. +1 – holi-java Aug 02 '17 at 15:32
  • No, it's not, it's only a bad practice. – humazed Aug 02 '17 at 15:50
  • thanks, I got it. but you can't define any shadow variable in Java. In fact, Kotlin defined another local variable for that, you also can change the local variable type, e.g: `var i:String = "foo"`. – holi-java Aug 02 '17 at 15:51