Kotlin中的交换功能 [英] Swap Function in Kotlin

查看:484
本文介绍了Kotlin中的交换功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了解决方案

完全不需要Kotlin中的交换功能.您可以使用现有的函数,例如:

var a = 1
var b = 2

a = b.also { b = a }

println(a) // print 2
println(b) // print 1

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?

解决方案

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

这篇关于Kotlin中的交换功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆