Kotlin Type Inference

| Page Views: 61

Type Inference is the ability of the compiler to automatically figure out the type of an expression from the information supplied in an expression.


var message = "Hello World"
val info= "This is me"
var age = 50
var distance = 243672L
var balance = 6252.20
  • Unlike Java in Kotlin you don't have to always include the type of a variable.

  • This is an ability akin to dynamic languages like Python,Ruby and Javascript. However Kotlin itself is a fully strongly typed programming language.

  • The Kotlin compiler will infer the types from the values of our variables.

  • Hence to utilize type inference you must supply a value, otherwise you get a compile-time error. If you don't have a value then specify the type explicitly.

Advantaes of Type Inference in Kotlin

  1. Reduces boilerplate code making our code more compact. Yet we still keep the type safety we expect from a strongly typed language.
  2. Not only is type inference in values and variables but also closures and single line functions.


fun main(args: Array<String>){
    var message = "Hello World"
    val info= "This is me"
    var age = 50
    var distance = 243672L
    var balance = 6252.20

    println("Message: "+message)
    println("Information: "+info)
    println("Age: "+age)
    println("Distance: "+distance)
    println("Balance: "+balance)


RESULT Here's what we get on running the project:

Message: Hello World
Information: This is me
Age: 50
Distance: 243672
Balance: 6252.2

Best Regards.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section.

About Me.

After completing his Software Engineering bachelors program, Oclemy(Clement Ochieng) these days is a man of two lives. At day he works for a startup in Nairobi, Kenya. At night he works tirelessly on building ProgrammingWizards TV, a tv channel for student coders and this website to help share the source code. In between he practices Meditation and Self actualization to help him keep balance. He also likes going for long solo walks to connect more with nature.


What do You Think

Previous Post Next Post