Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap Function in Kotlin

Tags:

kotlin

is there any better way to write generic swap function in kotlin other than java way described in How to write a basic swap function in Java.

Is there any kotlin language feature which can make generic swap function more concise and intuitive?

like image 909
Akshar Patel Avatar asked Jul 28 '17 15:07

Akshar Patel


People also ask

What is a swap function?

“Swap” can be used to drop one class and simultaneously add another. By swapping rather than dropping and then adding, you ensure that you will not give up your spot in one class and be unable to enroll in the other.

How do you swap arrays in Kotlin?

If your input is an array, you can use the Collections. swap() function to swap two elements in it. Since the Collections. swap() function accepts a list, you can get a fixed-size list “backed” by the array.

What is the syntax of swap function?

Syntax. constexpr void swap( T2 (&a)[N], T2 (&b)[N]); // Swaps the arrays a and b.


1 Answers

No need a swap function in Kotlin at all. you can use the existing also function, for example:

var a = 1 var b = 2  a = b.also { b = a }  println(a) // print 2 println(b) // print 1 
like image 195
holi-java Avatar answered Sep 21 '22 05:09

holi-java