Skip to Content
Course content

5: Types and Type Inference

Click on the "Edit" button in the top corner of the screen to edit your slide content.

If you're coming from a background in Java or C++, your first instinct in Kotlin will probably be to label every single variable you create. It feels safer. You want to be absolutely certain that the compiler knows exactly what's going on, and you want the person reading your code six months from now to know exactly what a variable is without having to hover their mouse over it in an IDE.

The Noise of Over-Declaration

When I first started with Kotlin, I wrote code that looked like this. I was treating it like a strictly typed manifest where nothing was left to chance:

val username: String = "dev_guru"
val loginAttempts: Int = 3
val isAccountLocked: Boolean = false
val sessionTimeout: Double = 30.5

Now, there is nothing technically "wrong" here. The code compiles, it's type-safe, and it's explicit. But if you look at it from a professional maintenance perspective, it's noisy. I'm telling the compiler that "dev_guru" is a String. Obviously, it's a String. The quotes literally tell the compiler that. By explicitly declaring : String, I'm not adding any new information; I'm just repeating myself. In a small example, it's a nuisance. In a 500-line class, this redundancy creates visual clutter that actually makes it harder to spot the logic because your eyes have to skip over the boilerplate type declarations every time.

Letting the Compiler Do the Heavy Lifting

Kotlin uses type inference, which is just a fancy way of saying the compiler is smart enough to look at the value you're assigning and figure out the type for you. I prefer to write the same logic like this:

val username = "dev_guru"
val loginAttempts = 3
val isAccountLocked = false
val sessionTimeout = 30.5

I've stripped away the noise, but I haven't lost any type safety. username is still a String; it's not some dynamic "anything goes" variable. If I try to assign an integer to it later, the compiler will still scream at me. This is the sweet spot of Kotlin: you get the brevity of a dynamic language like Python, but the iron-clad safety of a statically typed language. It makes the code breathe. You focus on the intent (the name and the value) rather than the implementation detail (the type).

Where Inference Fails and Clarity Wins

Now, I don't want you to go overboard and delete every type declaration in your project. There are specific moments where inference is actually a liability. The most common case is when you're declaring a variable without initializing it immediately, or when the value comes from a complex function where the return type isn't obvious.

Imagine you're calling a function from a third-party library:

// This is ambiguous to a human reader
val result = service.processData() 

If I'm reviewing your pull request, I have to go find the definition of processData() to know if result is a User, a Boolean, or a List<Error>. In this case, I'll actually recommend you be explicit. I'll write val result: ProcessResponse = service.processData(). By doing this, I'm documenting the code for my teammates. I'm saying, "I expect this function to return a ProcessResponse, and if it doesn't, I want the compiler to tell me right here."

As a rule of thumb: if the value is a literal (like a string or number), let the compiler infer it. If the value comes from a complex operation or is part of a public API that others will depend on, be explicit. It's a balance between brevity and communication.




📋 Practical Task

Refactoring the UserSession Manager

You've been handed a legacy piece of code written by an engineer who was obsessed with explicit typing. Your task is to refactor the UserSession object to use Kotlin's type inference where it makes sense, while keeping explicit types where they provide necessary clarity for the reader.

Requirements:

  • Remove explicit type declarations for all variables initialized with literals (Strings, Booleans, Numbers).
  • Keep the explicit type for the lastLoginDate variable, as it is initialized by a function call DateUtils.getCurrentTimestamp() and the type isn't immediately obvious to a reader.
  • Ensure the code remains functionally identical.
// Refactor this code
val sessionToken: String = "ABC-123-XYZ"
val isExpired: Boolean = false
val retryCount: Int = 0
val lastLoginDate: Long = DateUtils.getCurrentTimestamp()
val serverIp: String = "192.168.1.1"
Rating
0 0

There are no comments for now.

to be the first to leave a comment.