"with" 函数的用法

Usage of "with" function

有人可以向我解释一下 "with" 函数的用途吗?

签名

public inline fun <T, R> with(receiver: T, f: T.() -> R): R = receiver.f()

文档

Calls the specified function f with the given receiver as its receiver and returns its result.

我发现它在这个项目中的使用Antonio Leiva。它用于移动视图:

fun View.animateTranslationY(translationY: Int, interpolator: Interpolator) {
    with(ObjectAnimator.ofFloat(this, "translationY", translationY.toFloat())) {
        setDuration(context.resources.getInteger(R.integer.config_mediumAnimTime).toLong())
        setInterpolator(interpolator)
        start()
    }
}

我以为我知道我转给

的意思
fun View.animateTranslationX(translationX: Int, interpolator: Interpolator) {
    with(ObjectAnimator()) {
        ofFloat(this, "translationX", translationX.toFloat())
        setDuration(context.resources.getInteger(R.integer.config_mediumAnimTime).toLong())
        setInterpolator(interpolator)
        start()
    }
}

但它无法编译...但我认为 ObjectAnimaton 是接收器,它得到了我将在 {} 括号中调用的所有内容。任何人都可以解释真正的含义并提供一个基本的例子 - 至少比这更基本吗? :D

我想我理解了 "with" 所做的事情。看代码:

class Dummy {
    var TAG = "Dummy"

    fun someFunciton(value: Int): Unit {
        Log.d(TAG, "someFunciton" + value)
        }
    }

    fun callingWith(): Unit {
    var dummy = Dummy()
    with(dummy, { 
        someFunciton(20) 
    })

    with(dummy) {
        someFunciton(30)
    }

}

如果我 运行 这段代码,我会用 20 个参数调用 someFunciton,然后用 30 个参数调用。

所以上面的代码可以转换成这样:

fun View.animateTranslationX(translationX: Int, interpolator: Interpolator) {
    var obj = ObjectAnimator()
    with(obj) {
        ofFloat(this, "translationX", translationX.toFloat())
        setDuration(context.resources.getInteger(R.integer.config_mediumAnimTime).toLong())
        setInterpolator(interpolator)
        start()
    }
}

而且我应该工作 - 所以我们必须有 var.

这个想法与 Pascal 中的 with 关键字相同。
无论如何,这里有三个具有 相同 语义的示例:

with(x) {
   bar()
   foo()
}
with(x) {
   this.bar()
   this.foo()
}
x.bar()
x.foo()