有没有人能解释一下“有”功能是用来做什么的?
签名
public inline fun <T, R> with(receiver: T, f: T.() -> R): R = receiver.f()文档
调用指定的函数f,以给定的接收器作为接收方,并返回其结果。
我发现它在安东尼奥·莱瓦这个项目中使用。它用于移动视图:
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
发布于 2015-10-21 06:13:10
这个想法与Pascal中的with关键字相同。
总之,这里有三个具有相同的语义的示例:
with(x) {
bar()
foo()
}with(x) {
this.bar()
this.foo()
}x.bar()
x.foo()发布于 2015-10-19 14:04:32
我想我明白“用”做什么了。看看代码:
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)
}
}如果我运行这段代码,就会得到一个someFunciton调用,调用20,然后调用30 param。
因此,上面的代码可以转换为:
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()
}
}我应该工作-所以我们必须有瓦尔。
https://stackoverflow.com/questions/33198514
复制相似问题