Kotlin Type Inference

April 18, 2018 Oclemy Kotlin Data Types 1 minute, 8 seconds

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.

Comments