When is a Type not a Type? Kotlin in the IDE

This article explains the ‘show type hints’ feature of IntelliJ. To get to see those sweet variable types you desire but not change any of the code conventions in your place of work.

When is a Type not a Type? Kotlin in the IDE

This article explains the ‘show type hints’ feature of IntelliJ. To get to see those sweet variable types you desire but not change any of the code conventions in your place of work.

I like Kotlin as much as the next Android programmer, however I don’t know about you but I miss my Java Type declarations! It’s ok when I’ve wrote the code 5 minutes ago I’ll remember the type, but reading old code / others code / legacy code. I often am wondering, what is the type?

Local variables are typically declared and initialized at the same time, in which case the type of the variable is inferred to be the type of the expression you initialize it with:

https://kotlinlang.org/docs/tutorials/kotlin-for-py/declaring-variables.html

To figure the Type out in the past, I’ve used a variety of inspections including using the AndroidStudio short cut to ‘specify the type explicity’. This adds the Type to the declaration, I see what it is, then remove it again (due to project conventions, or not wanting to have a huge diff of changes).

I know I can also hover over the method or variable to see the type, but these tool tips sometimes return the generics rather than the actual type it will be, and hovering feels so slow sometimes.

Until now! Now I have found the IntelliJ/Android Studio shortcut for “show type hints”. Toggling this on, shows each variable as declaring the type but only as a hint so it’s not in your codebase, nobody is the wiser – except you!

Show Local Variable Type Hints

The above code is some typical Kotlin, but with no darn Types for the variables.

With the shortcut ALT + ENTER you can get the ‘context actions’, in this menu is just what we want. Arrow down to Show local variable type hints and press ENTER.

Below shows the same code with, show local variable type hints, toggled on. Looks good to me!

Unfortunetely I have only found this option in the contextual options menu, and so you have to turn it on separately for each type of variable. For instance below is the toggled off and on versions for properties:

That’s it! Enjoy your new secretly Typed Kotlin code, without anyone else complaining of all the “Legacy Java Types” in the Kotlin codebase. That is until you screenshare and they ask “if someone where to be interested how do they turn on such a feature…”. 😉


Footer

And to confirm, this is what it would be like if I declared the variable:

And what I get if I hover over or click into the returning Type method:

2 thoughts on “When is a Type not a Type? Kotlin in the IDE

  1. You can find it (and set it permanently) in Settings -> Editor -> Inlay Hints -> Kotlin

Comments are closed.