Generic swap: Difference between revisions

Content added Content deleted
(Add Plain English)
(→‎{{header|Kotlin}}: added another possible solution)
Line 1,691: Line 1,691:
=={{header|Kotlin}}==
=={{header|Kotlin}}==
As Kotlin does not support passing parameters by reference and tuples cannot be destructured automatically to pre-existing variables, it's just as easy to swap variable values 'inline' rather than using a function. However, here's one of way of doing it generically using the latter:
As Kotlin does not support passing parameters by reference and tuples cannot be destructured automatically to pre-existing variables, it's just as easy to swap variable values 'inline' rather than using a function. However, here's one of way of doing it generically using the latter:
<syntaxhighlight lang="scala">// version 1.1
<syntaxhighlight lang="kotlin">

fun <T> swap(t1: T, t2: T) = Pair(t2, t1)
fun <T> swap(t1: T, t2: T) = Pair(t2, t1)


fun main(args: Array<String>) {
fun main() {
var a = 3
var a = 3
var b = 4
var b = 4
Line 1,719: Line 1,718:
e = false
e = false
</pre>
</pre>

You can also explicitly create a container class and swap the value that it contains (but this is a bad idea in practice):
<syntaxhighlight lang="kotlin">
data class Ref<T>(var value: T) {
fun swap(other: Ref<T>) {
val tmp = this.value
this.value = other.value
other.value = tmp
}
override fun toString() = "$value"
}
fun main() {
val a = Ref(1)
val b = Ref(2)
a.swap(b)
println(a)
println(b)
}
</syntaxhighlight>


=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==