Correct Kotlin variable declaration

Computer Science

ScanSolve AI Answer

Answer

In Kotlin, variables are declared using either val for read-only (immutable) variables or var for mutable variables.

val (immutable variable):

val variableName: Type = initialValue

Example:

val message: String = "Hello, Kotlin!"
val year = 2023 // Type inference

var (mutable variable):

var variableName: Type = initialValue

Example:

var count: Int = 0
var name = "Alice" // Type inference

Kotlin also supports type inference, meaning you can often omit the type declaration if the initial value makes the type clear.

Was this helpful?

Still stuck on this one?

Ask a follow-up, and the answer starts from this question.

Got a different question?Ask your own question