-1

I often have the situation, that I want to change variables var1 to var2 .

But in a function, I cannot change the input parameters. How could i do it with a "function-call" The variables are sometimes strings, integers oder objects from Android Studio GUI

I do it like this:

tmp = var1
var1 = var2
var2 = tmp

or

tmp = name1.text.toStirng()
name1.text.toString() = name2.text.toString()
name2.text.toString() = tmp

as a function I think it is not possible

fun switch_vars(var1:String, var2:String)

it does not work.

How can is do it, because i have plenty of such situations

user3367867
  • 565
  • 1
  • 7
  • 19

1 Answers1

0

Even for data types that are passed by reference in Kotlin (most everything not primitive), this cannot be achieved by a function of your creation because all parameters are treated as vals, ie they cannot be reassigned.

The options in the thread provided in denvercoder's comment are your best bet.

Jacob
  • 1,697
  • 8
  • 17
  • In Java, method parameters are not read-only, and yet changing them still has no effect on the variables used to pass them. They are still local copies to the method. Kotlin has the extra restriction to make code less ambiguous. – Tenfour04 May 31 '20 at 23:54
  • Java can definitely affect non-primitive variables outside of the current scope. Not in the way the question describes, but Java parameters are not read-only, for example, changing array indices Java: ``` class Scratch { public static void main(String[] args) { int[] a = new int[] {1, 2, 3}; System.out.println(a[0]); change(a); System.out.println(a[0]); } public static void change(int[] a) { a[0] = 3; } } Output: 1 3 ``` Kotlin ``` var a = arrayOf(1,2, 3) println(a[0]) fun swap(a: Array) { a[0] = 3 } println(a[0]) Output: 1 1 ``` – Jacob Jun 01 '20 at 00:17
  • 2
    It can affect the mutable objects the external variables are pointing to, but not the external variables themselves. A method doesn’t even know what variable was holding the reference that is passed to it. It just gets a copy of the reference, in a new mutable variable. – Tenfour04 Jun 01 '20 at 00:54