Kotlin generic function: Swap variable values
Kotlin Function: Exercise-21 with Solution
Write a Kotlin generic function that swaps the values of two variables.
Sample Solution:
Kotlin Code:
fun <T> swap(array: Array<T>) {
require(array.size == 2) { "Array must contain exactly two elements" }
println("Before swap: ${array[0]}, ${array[1]}")
val temp = array[0]
array[0] = array[1]
array[1] = temp
println("After swap: ${array[0]}, ${array[1]}")
}
fun main() {
val numbers = arrayOf(44, 90)
swap(numbers)
val strings = arrayOf("Hello", "World")
swap(strings)
}
Sample Output:
Before swap: 44, 90 After swap: 90, 44 Before swap: Hello, World After swap: World, Hello
Explanation:
In the above exercise -
- The "swap()" function is defined with a generic type T. It takes an array as a parameter, which can hold elements of any type.
- The function checks if the array contains exactly two elements using the require function. If the condition is not met, it throws an exception with the specified error message.
- A temporary variable temp is declared and assigned the value of the first element in the array (array[0]).
- The first element of the array is then assigned the value of the second element (array[1]), effectively swapping their values.
- Finally, the second element is assigned the value of temp, completing the swap operation.
- After the swap, the function prints the updated values of the array elements using string interpolation.
- In the main function, two arrays are created: numbers containing integers and strings containing strings.
- The swap function is called twice, once with the numbers array and once with the strings array. This demonstrates how the swap function can be used with different types.
Kotlin Editor:
Previous: Calculate the square of a number.
Next: Calculate the sum of arithmetic or geometric series.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/kotlin-exercises/function/kotlin-function-exercise-21.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics