Thursday, February 8, 2018

Kotlin type inference and readability

I started reading "Kotlin in Action", and as I write this, I'm in the second chapter.

Having used Java for years, what worries me a little is whether type inference impairs readability.

Let's say we take the example in the book,

   fun max (a : Int, b : Int) = if (a > b) a else b

For someone reading this code, it's not obviously as to what the return type is, unless they read and understand the implementation (the 'if' expression on the right in this case).
Although the return type of the function is optional only for functions with an expression body like the example above, and not with a block body, it's not totally comforting. For instance,

   fun compute(a : Int, b : Int) = if (a > b) xyz(a, b) else abc(a, b)


Also, in the first chapter, there's an example regarding automatic typecasting:

   if (value is String)  {
       // value is now typed as String
      println value.toUpperCase()
   }

In the example above, the reference 'value' gets casted automatically within the body of the 'if' block to String, which is why you can call toUpperCase without casting it to String explicitly. What this means is that whenever I see a variable in any place in the code, I can't keeps its declaration-time-type in mind while reading the code to know what type it is of; instead, I should always rely on the IDE to tell me what exactly it is. This is quite unsettling as well.