Operator function like asXxx() for overwriting the type cast

I think you are not the first to suggest something like this. I personally don’t like the idea of adding something like this. It neither adds new functionality nor makes the code more readable. It just hides information, because you are no longer able to differentiate between casting to a different type or generating a wrapper object.
Also there is the problem that often when we talk about casting a object form one type to another we think about cast-functions that generate a new distinct object. asXXX however normally means that the objects represent the same state and changes on one will be reflected in the other (at least in kotlin).
That means that we would probably also need to create a similar operator to which would work in that way.

About smart casts: I think this feature has a small problem with smart casts. Mainly the syntax you use in your example.
Although (point as? Vector) ?: return should work to smart cast point to a Vector it’s the wrong syntax to use form an idiomatic viewpoint. if(point !is Vector) return is far more readable and expresses the intention much more clearly IMO. The problem is that I don’t think your proposal should change the way the is operator works, therefore making your code fail.

Also there is the minus 100 points rule

1 Like