Shortcut to inline casting without Parantheses

Hi all,

I have just passed by something last day, and that was that when I was parsing some sqlite row on Android I faced a bit of a problem , where I was trying to instantiate an instance of a data holder class … So what an example of what I ended up with was like this

(map["column1"] as Long).toInt(),
(map["column2"] as Long).toWhatever()

and it goes on and on …

So i thought why wouldn’t we make a small change so the syntax would be more like this


This would help getting rid of the parantheses which are a pain each time you forget them …

More we can add the safe operator like so


What do you think guys ?

Adding new syntax to the language requires much stronger motivation than “I had this one task where I had to write this code which was a little bit verbose”. Casts are not that common in Kotlin code, and the syntax Kotlin has for them is much easier to read than the backslash operator (which is not used for type casts in any other language that I’m aware of).

1 Like

I suppose you’re correct, so I thought instead of actually making a new syntax , just allow the cast to go without parentheses if possible.

x as Long.toInt()

Would that be possible ?

No, this can’t be parsed unambiguously.

I see , thank you , sorry for any inconvenience !

If it bothers you that much, you can write a “helper”

inline fun <reified T> Any.cast() = this as T

// Use this way

Unfortunately there are no generic properties (probably wouldn’t be a good design either) so you’ll have to live with the parentheses.


Brilliant idea sir ! thanks for the help ! It’s nice how simple and functional Kotlin can be

Another approach to this problem is not from the language side, but from the tooling: IDEA 2016.3 is going to support postfix code completion templates and Kotlin is too:

One of such templates is parenthesis. So, when you write someValue as T, then .par and press TAB, it magically gets replaced with (someValue as T).

That would be really helpful !
For the time being I used the function by pdvrieze and made a simple addition

inline fun <reified T> Any.cast(x : T) = this as T

this way I can benefit from Kotlin’s type inference , so that casting to int would be like

x.cast(1) + 2