United121
United121

Reputation: 729

Usage of "with" function

is there somebody who can explain me what "with" 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 its receiver and returns its result.

And I found its using on this project Antonio Leiva. It was using for moving view :

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 was thinking that I know the meaning to I transfer it to

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 doesn't compile ... But I think that ObjectAnimaton is receiver and it get everything what I will call in {} bracket. Can anybody explain the real meaning and provide a basic example - at least more basic than this? :D

Upvotes: 7

Views: 300

Answers (2)

voddan
voddan

Reputation: 33769

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

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

Upvotes: 5

United121
United121

Reputation: 729

I think that I understood what "with" do. Look at 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 calling of someFunciton with 20 and then with 30 param.

So the code above can be tranfer 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 - so we have to have var.

Upvotes: 0

Related Questions