Shortcut to inline casting without Parantheses


#1

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

Dataholder(
(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

map["column1"]\Long\.toInt()

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

map["column1"]\Long\?.toInt()

What do you think guys ?


#2

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).


#3

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 ?


#4

No, this can’t be parsed unambiguously.


#5

I see , thank you , sorry for any inconvenience !


#6

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

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

// Use this way
map["column1"].cast<Long>().toInt()

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


#7

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


#8

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: https://blog.jetbrains.com/kotlin/2016/11/kotlin-1-0-5-is-here/.

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).


#9

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