Kotlin Type Inference


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

e.g

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.

Example.

fun main(args: Array<String>){
    //TYPES AUTOMATICALLY INFERED
    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. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think

Dear readers drop us your comments below. We are building a community of students and learners. Start by dropping us your suggestions below. What tutorials do you want us to do for example? Where can we improve? What are some awesome resources out there? Do you have any code you want to share with us?
By the way that example or snippet you have lying in your computer can really help beginner programmers. We can share it here with other students.

Previous Post Next Post