Using the c function

is there anyone who can explain to me what the c function is used for?

Signature

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

Doc

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

And I found its use in this project by Antonio Leiva . It was used to move:

 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() } } 

I thought I knew the point of passing it on

 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() } } 

but it does not compile ... But I think that ObjectAnimaton is the receiver, and it gets everything that I will name in the bracket {} . Can someone explain the real meaning and provide a basic example - at least simpler than this ?: D

+6
source share
2 answers

The idea is the same as with keyword in Pascal.
Anyway, here are three examples with identical semantics:

 with(x) { bar() foo() } 
 with(x) { this.bar() this.foo() } 
 x.bar() x.foo() 
+3
source

I think I understood what to do with. Take a look at the code:

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

If I run this code, I get one call to someFunciton with 20, and then with 30 parameters.

So the above code can be redirected to this:

 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() } } 

and I should work - therefore we should have var.

0
source

All Articles