我想写修改“this”的扩展函数,例如:
var a = false
a.toggle() // now a contains false
或
var a = 1
a.increment() // now a contains 2
在 Kotlin 中可以吗?
我可以创建返回修改后的值的扩展函数,但不修改“this”,但我想要更方便!看起来 Swift 可以做到。
最佳答案
尚不支持对变量的引用,但您可以创建扩展函数以与 property references 一起使用:
fun KMutableProperty0<Boolean>.not() = set(get().not())
fun KMutableProperty0<Int>.inc() = set(get().inc())
var a = false
var b = 1
fun main(vararg args: String) {
::a.not()
// now `a` contains `true`
::b.inc()
// now `b` contains `2`
}
或者,如果您希望扩展函数在设置时返回新值:
fun KMutableProperty0<Boolean>.not(): Boolean = get().not().apply(setter)
fun KMutableProperty0<Int>.inc(): Int = get().inc().apply(setter)
关于kotlin - 修改扩展函数中的 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40004168/