“with”功能的用法
有没有人可以解释我用什么“用”功能?
签名
public inline fun <T, R> with(receiver: T, f: T.() -> R): R = receiver.f()
文件
用给定的接收者作为接收者调用指定函数f并返回结果。
我发现它在这个项目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
Pascal中的关键字一样。
无论如何,这里有三个具有相同语义的样本:
with(x) { bar() foo() }
with(x) { this.bar() this.foo() }
x.bar() x.foo()
我认为我明白了什么“与”做。 看代码:
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的调用,然后是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() } }
我应该工作 – 所以我们必须有变种。