1

In Kotlin, specifying the return types of functions and the types of variables is usually optional but can be optionally included.

I've encountered a few benefits of including them:

  • It sometimes makes type errors more understandable as when types don't match it helps the compiler determine which is wrong and which is right.
  • It makes the code more explicit and therefore more clear
  • It might improve build times. I haven't found a definitive answer on how big an effect it has though.

On the other hand, there are a couple of benefits of not including type declarations:

  • Less typing
  • More concise code

I know the Kotlin coding conventions say to include them in the interface of a library, which makes sense but doesn't apply to most of my code.

I believe in the Haskell community where type declarations are also optional, it's considered a good idea to always explicitly declare the types of functions.

Is there any kind of well regarded convention on when we should include them in Kotlin?

1

I don't believe there's an effect on build times. My understanding is type inference gets run no matter what, and if you explicitly specify types, it just checks that the specified type unifies with the expected type.

The general guidance in type-inferred languages is to specify the types of functions, so your interface is more stable, and so programmers don't have to read your entire function body in order to know how to call it. The exception here is very small, private, one-liner helper-type functions.

Aside from that, I explicitly specify types on intermediate results when I frequently get the wrong type during development, or have a hard time figuring out what the type is during development. Sometimes this is for an inference limitation like getting a None when you needed an Option[Int]. Sometimes this is for programmer errors like accidentally ending up inferring an Any, or accidentally getting a List[Int] when you need a List[List[Int]], or vice versa. Or when your compiler reports a type error on line 10, but the root cause is on line 3.

Basically, add type annotations when they speed you up, and omit them when they would just add clutter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.