Type Inference
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 6 of 93.
Kotlin can automatically figure out the type of a value. This is called type inference:
fun main() {
val name = "Alice" // Kotlin infers this is a String
val age = 25 // Kotlin infers this is an Int
val price = 9.99 // Kotlin infers this is a Double
}But you can also explicitly declare the type using a type annotation. You write a colon after the name, followed by the type:
fun main() {
val name: String = "Alice"
val age: Int = 25
val price: Double = 9.99
val isActive: Boolean = true
}Type annotations are useful when:
- You want to be extra clear about what type a value is
- You declare a variable without an initial value
fun main() {
var score: Int // Declared but not yet assigned
score = 100 // Assigned later
}Without the type annotation, Kotlin wouldn't know what type score should be.
Challenge
BeginnerCreate four val declarations without explicit type annotations: city holding "Oslo", platform holding 4, fare holding 12.5, and isExpress holding false. Let Kotlin infer their types. Print their values on four separate lines in that order.
Try it yourself
fun main() {
// Declare the four values without type annotations.
// Print them in the requested order.
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic InputPractice on your own: Kotlin playground