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")
}
CodePudding user response:
While I have two suggestions below, I want to start with a recommendation against either of them, at least in this simple example.
It's usually a lot more clear to optimise code for developers to read in the following ways:
- create an extra variable with a descriptive name
- prefer
val
overvar
to avoid accidental mutations - and try to make the code 'linear', so the operations can be read from top-to-bottom without jumping between functions
- avoid code that needs an IDE to see what the type-hints are
And I'll trust that the compiler will make make the code performant.
fun main() {
val x = 5
val y = 10
val newX = y
val newY = x
println("X = $newX, Y = $newY")
}
Local function
You could use a local function to perform the swap, as the function will still be able to access the original values.
fun main() {
var x = 5
var y = 10
fun swap(originalX: Int, originalY: Int) {
y = originalX
x = originalY
}
swap(x, y)
println("X = $x, Y = $y")
}
Scope function
This could be code-golfed into one line
- use
to
to create aPair<Int, Int>
, - and a scope function to use the result.
fun main() {
var x = 5
var y = 10
(x to y).apply { x = second; y = first }
println("X = $x, Y = $y")
}
One line? Yes. More difficult to read? I think so.