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

bookExplicit Type Declaration

Sveip for å vise menyen

Kotlin usually infers the type of a variable from its initializer, letting you write concise code. However, there are important reasons to use explicit type declarations. Declaring types explicitly can make code clearer, especially for other developers who may not know what type a variable should be. This practice also helps prevent errors when the initializer's type is not obvious, or when you want to avoid accidental type changes in the future. Explicit types are particularly helpful in complex codebases, when working with APIs, or when you want to ensure a variable has a specific type for consistency.

Main.kt

Main.kt

copy
12345678910111213141516171819202122
package com.example fun main() { // Type inferred by Kotlin val inferredInt = 42 val inferredString = "Hello, Kotlin!" // Explicit type declarations val explicitInt: Int = 42 val explicitString: String = "Hello, Kotlin!" // Example where explicit type helps val number = 42 // Kotlin infers Int val longNumber: Long = 42 // Explicitly Long println("Inferred Int: $inferredInt") println("Explicit Int: $explicitInt") println("Inferred String: $inferredString") println("Explicit String: $explicitString") println("Number (Int): $number") println("Long Number (Long): $longNumber") }

Looking at the code above, you see both inferred and explicit type declarations. When you write val inferredInt = 42, Kotlin understands the type is Int from the value. But with val explicitInt: Int = 42, you make the type clear for anyone reading the code. This is especially useful if the initializer is not a simple literal, or if you want to ensure the variable stays an Int even if the initializer changes later. Declaring val longNumber: Long = 42 is a good example—without the explicit type, Kotlin would make number an Int, but you might need a Long for compatibility or to avoid overflow. In larger codebases, or when maintaining code with multiple contributors, explicit types reduce confusion and help prevent subtle bugs.

question mark

Why might you choose to declare a variable's type explicitly in Kotlin?

Select the correct answer

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 2. Kapittel 2

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Seksjon 2. Kapittel 2
some-alt