我想编写修改this的扩展函数,例如:

var a = false
a.toggle() // now a contains false

or

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`
}

Or if you'd rather the extension functions return the new value along with setting it:

fun KMutableProperty0<Boolean>.not(): Boolean = get().not().apply(setter)
fun KMutableProperty0<Int>.inc(): Int = get().inc().apply(setter)

Kotlin相关问答推荐

Kotlin:有限的并行性并不是限制并行性

在Kotlin中,我是否可以访问已知的WHEN子句值?

在构造函数中创建内部类实例时,只能使用包含类的接收器调用内部类的构造函数

房间数据库操作中的协程取消

如何在数据类中删除空格 (String)?

Kotlin .如何用从 1 到 90 的 5 个唯一数字填充列表中的每一行?

Kotlin 启动与启动(Dispatchers.Default)

从 HashMap 检索时的 NPE,即使 containsKey() 在多线程环境中返回 true

如何将glide显示的图像下载到设备存储中.Kotlin

T except one class

为什么没有remember 的 mutableStateOf 有时会起作用?

Kotlin 中的部分类委托

IntelliJ 不会根据 ktlint 的期望对 Kotlin 导入进行排序

找不到 androidsdk.modules

如何处理 Kotlin 中的异常?

更新到版本4.10.1/4.10.2后 Gradle 同步失败

如何在Kotlin中创建填充空值的通用数组?

如何在Kotlin中使用ViewModelProviders

在 IntelliJ Idea 中未为 Kotlin @ConfigurationProperties 类生成 spring-configuration-metadata.json 文件

Kotlin 中的限制函数