Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Type Inference | Type Inference and Conversion
Practice
Projects
Quizzes & Challenges
Quizzes
Challenges
/
Kotlin Data Types

bookType Inference

Swipe to show menu

Kotlin offers a feature called type inference, which lets you declare variables without explicitly stating their type. Instead, the Kotlin compiler examines the value you assign to a variable and automatically determines its type for you. This leads to cleaner, more concise code because you do not have to repeat type information when it is obvious from the assigned value. Type inference makes your code easier to read and maintain, especially when working with simple values or when the type can be easily inferred from the context.

Main.kt

Main.kt

copy
1234567891011121314151617
package com.example fun main() { // Variable with explicit type declaration val explicitInt: Int = 10 val explicitString: String = "Kotlin" // Variable with type inference (no type specified) val inferredInt = 10 val inferredString = "Kotlin" // Output the types using reflection println("explicitInt is of type: ${explicitInt::class.simpleName}") println("inferredInt is of type: ${inferredInt::class.simpleName}") println("explicitString is of type: ${explicitString::class.simpleName}") println("inferredString is of type: ${inferredString::class.simpleName}") }

Type inference works best when the compiler can clearly identify the type from the value assigned. In the example above, both val inferredInt = 10 and val inferredString = "Kotlin" allow Kotlin to infer the types as Int and String, just as if you had declared them explicitly. You might still need to specify the type in more complex situations, such as when you declare a variable without assigning a value immediately, or when the type could be ambiguous. In those cases, providing an explicit type helps the compiler and makes your code clearer to other developers.

question mark

What does Kotlin use to determine a variable's type when you don't specify it?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 2. ChapterΒ 1

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

SectionΒ 2. ChapterΒ 1
some-alt