Type Inference
Scorri per mostrare il 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
1234567891011121314151617package 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.
Grazie per i tuoi commenti!
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione