Autocast with apply


#1
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?


#2

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


#3

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


#4

Well you can do something like:

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

#5

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


#6

@tieskedh
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?


#7

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…