Dmi*_*nko 9 kotlin kotlin-extension
我想编写修改"this"的扩展函数,例如:
var a = false
a.toggle() // now a contains false
Run Code Online (Sandbox Code Playgroud)
要么
var a = 1
a.increment() // now a contains 2
Run Code Online (Sandbox Code Playgroud)
在Kotlin有可能吗?
我可以创建返回修改值的扩展函数,但保留"this"未修改,但我想要更方便!看起来Swift可以做到这一点.
尚不支持对变量的引用,但您可以创建扩展函数以与属性引用一起使用:
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`
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您希望扩展函数在设置它的同时返回新值:
fun KMutableProperty0<Boolean>.not(): Boolean = get().not().apply(setter)
fun KMutableProperty0<Int>.inc(): Int = get().inc().apply(setter)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1433 次 |
| 最近记录: |