kotlin扩展function不知道这个东西是如何工作的

我是一个非常新的学习Kotlin。 到目前为止,一切都是可以理解的,到今天为止我已经遇到了一些威胁我的代码。 我搜索了很多,并对这段代码做了一些研究。 这是我需要了解的两个扩展函数

private fun T ?.useOrDefault(default: R, usage: T.(R) -> R) = this?.usage(default) ?:default 

第二个

 inline fun  doubleWith(first: F, second: S, runWith: F.(S) -> Unit) { first.runWith(second) } 

用法

 a.useOrDefault(100) { getInteger(R.styleable.ArcSeekBar_maxProgress, it) } set(progress) { field = bound(0, progress, Int.MAX_VALUE) drawData?.let { drawData = it.copy(maxProgress = progress) } invalidate() } 

我对lambda函数和高阶函数有了一个基本的理解,但是这个generics的函数实际上是作为一个初学者

提前感谢和赞赏

这两个function的主要function是,它们是根据官方文件的扩展function

为了声明一个扩展函数,我们需要在它的名字前加一个接收器types,即扩展types。 以下将交换函数添加到MutableList

 fun MutableList.swap(index1: Int, index2: Int) { val tmp = this[index1] // 'this' corresponds to the list this[index1] = this[index2] this[index2] = tmp } 

扩展函数中的this关键字对应于接收者对象(在点之前传递的对象)。 现在,我们可以在任何MutableList上调用这个函数

现在,如果你想要,你可以改变types为generics像这样

 fun  MutableList.swap(index1: Int, index2: Int) { val tmp = this[index1] // 'this' corresponds to the list this[index1] = this[index2] this[index2] = tmp } 

现在看一下函数useOrDefault正在接受调用者对象(在示例中为“a”),如果不是null,则运行函数“usage”,否则返回默认值。 由于用法是作为调用者的扩展函数,所以它可以执行“this?.usage()”

阅读这篇文章,这将有助于了解这个function

忍者在Kotlin的function

例如,doubleWith()方便地使用对象作为第一个参数,复杂expression式作为第二个参数,lambda作为第三个参数

 doubleWith(first = a, second = {complex expression}) { // first as this (like in with body) // and second as it (or explicit parameter name) // in lambda body ... }