how to define variable in kotlin
Defining Variables in Kotlin
To define a variable in Kotlin, you can use the val
and var
keywords. Here's an explanation for each step:
- Using
val
Keyword: - The
val
keyword is used to declare a read-only (immutable) variable. Once assigned, its value cannot be changed. - Example:
kotlin val pi = 3.14
This declares a variable
pi
with the value 3.14.Using
var
Keyword:- The
var
keyword is used to declare a mutable variable whose value can be changed after it is assigned. - Example:
kotlin var radius = 5
This declares a variable
radius
with the initial value of 5, which can be changed later in the code.Type Inference:
- In Kotlin, you can omit the variable's type if it can be inferred from the value assigned to it.
- Example:
kotlin val message = "Hello, World!"
Here, the type of
message
is inferred asString
because it is initialized with a string value.Explicitly Specifying Type:
- You can also explicitly specify the type of the variable when declaring it.
- Example:
kotlin val number: Int = 10
This declares a variable
number
of typeInt
with the initial value of 10.Nullable Variables:
- In Kotlin, you can declare variables as nullable by using the
?
operator after the type. - Example:
kotlin var name: String? = null
Here,
name
is a nullable variable of typeString
that can hold a null value.Lazy Initialization:
- You can also declare a variable without initializing it immediately by using the
lateinit
keyword. - Example:
kotlin lateinit var userName: String
This declares a variable
userName
of typeString
that will be initialized later in the code.Variable Naming:
- Variable names in Kotlin can contain letters, digits, and underscores. They cannot start with a digit.
- Example:
kotlin val userAge = 25
These are the various ways to define variables in Kotlin, allowing for flexibility and type safety in your code.