I had to swap 2 numbers in one line expression using no other variable except x and y.
So I wrote the following .c program to swapp two numbers with the given conditions and it works like charm.
int main() {
int x =5, y =2;
x = y-x+(y=x);
printf("X=%d, y=%d", x, y);
return 0;
}
But when i try to do the same in kotlin it gives me an error that
Assignments are not expressions, and only expressions are allowed in this context,
I can resolve this issue by introducing a third variable just like this. But I'm not allowed to have any other variable except x and y which are already given. So is there any other way I can do this in one line using any kotlin property?
Below is the kotlin program
fun main() {
var x = 5
var y = 10
x = y-x+(y=x)
println("X = $x, Y = $y")
}
a = b.also { b = a }x = x+y; y = x-y; x = x-ydoes the trick. If it has to be a single statement then TenFour's suggestion ofx = y.also{y = x}appears to work when testing in a Kotlin playgroundalsothing, or write a reusableswapfunction that takes property references so you can goswap(::a, ::b)or something like that