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
Kotlin Data Types

bookExplicit Type Declaration

Stryg for at vise menuen

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

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?

Vælg det korrekte svar

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 2. Kapitel 2

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

Sektion 2. Kapitel 2
some-alt