Why Kotlin has "postfix" syntax for type declaration?


For example I has class CoolMessageFactory. In some method I want to declare variable of this type.

In Java (with Idea) I can type:
  CMF <enter> <space> <enter>
And I get
  CoolMessageFactory coolMessageFactory

But in  Kotlin I should type:
  val  coolMessageFactory:CMF<enter>

Too long even if I omit last “CMF<enter>”.

Why Kotlin has “postfix” syntax for type declaration?


The main reasons for this kind of syntax lie in the area of the crucial new features we have added: type inference and higher-order funcitons. The Java-style syntax is pretty hostile to these features: they just don't fit in. Also, we find it easier to read the name of the entity before the type, and the code is read much more than written.

I understand your concern about the IDE experience, and we will address it on the IDE level: the idea is that you say

val cMF <Ctrl+Space> <Enter> = CMF()

and get

val coolMessageFactory = CoolMessageFactory()


If you're assigning a value you can use the introduce variable refactoring:

CMF <enter> -> CoolMessageFactory()

introduce variable -> val coolMessageFactory = CoolMessageFactory()

I use this all the time in Java.

If you’re not assigning a value it should also be possible to use live templates. e.g.


with the variables in the order TYPE, NAME.

That means the type of the variable would be known before the name and IntelliJ could use the type to suggest a name. Unfortunately it doesn’t work at the moment.