Autocast with apply

infix fun A.doAction(action: Action) : B= when {
    this is B-> apply { action() }
    else -> B(this, action)

I want to perform an action on an A-object.
However only a B-object can perform this action.
Therefor, if the object is not a B, i want to wrap it in a B.
I want to return the B-object from the function.
However, the autocast only works if I explicitly add this as a receiver object.
Is it possible for the compiler to figure this out by itself?


So what do you suggest ? That is B is enough in your context ?


yes, I would like to see that the code above compiles


Well you can do something like:

infix fun A.doAction(action: Action) : B = when (this) {
    is B -> apply { action() }
    else -> B(this).apply { action() } 


Well my code doesn’t work because of the first case. so the type inference of this is not strong enough


If I reproduced it correctly, the type inference problem should go away if you place explicit this. before apply.

Could you report this problem to the issue tracker, better providing the details about what are the A, B and Action types?


I looked at my question at another way, and the thing I want is not possible.
My question was if the its in the following example could be the same…

infix fun A.doAction(action: Action) {
    if(this is B) {
       this.also{ it -> }
       also{ it -> }

But, I now have the answer: no, because it changes backwards-compatibility.
Sorry for taking your time…