kotlin
  1. kotlin-variable

Kotlin Variable

In Kotlin, variables are used to hold and store values. You can declare and initialize variables in Kotlin using the var and val keywords.

Syntax

var variableName: DataType = value 
val variableName: DataType = value 
  • var is used to declare a mutable variable whose value can be changed.
  • val is used to declare an immutable variable whose value cannot be changed.
  • variableName is the name of the variable.
  • DataType is the type of data the variable can hold.
  • value is the initial value assigned to the variable.

Example

var age: Int = 30
val name: String = "John"

Output

The output of the above example would be:

println(age) // 30
println(name) // John

Explanation

In the example above, age is a variable of type Int, and its initial value is 30. name is a variable of type String, and its initial value is John.

The var keyword is used to declare a mutable variable whose value can be changed in the future. On the other hand, val keyword is used to declare an immutable variable whose value cannot be changed once assigned.

In Kotlin, it is not necessary to specify the data type of the variable because Kotlin automatically infers the data type based on the value assigned to it. For example, if you assign a value of 25 to a variable, Kotlin will automatically infer that the variable is of type Int.

Use

  • Variables are used to store and manipulate data in your program.
  • You can use variables to keep track of user inputs, perform calculations, and control program flow.

Important Points

  • Kotlin supports both mutable and immutable variables.
  • You can declare variables without assigning an initial value. In that case, you must explicitly declare the data type of the variable.
  • You can also reassign a new value to a variable declared using var, but you cannot change the value of a variable declared using val.
  • You can use the lateinit keyword to declare a variable without initializing it.

Summary

In this tutorial, we learned about variables in Kotlin. We covered how to declare variables using the var and val keywords, their syntax, examples, output, explanation, use, important points, and summary.

Remember that variables are used to hold and store values in Kotlin, and they can be mutable or immutable depending on your code requirements.

Published on: