Wednesday, June 28, 2023

Kotlin Variables

 

Kotlin Variables

Variables are containers for storing data values.

To create a variable, use var or val, and assign a value to it with the equal sign (=):

Syntax

var variableName = value

val variableName = value

Ex:

var name = "John"

val birthyear = 1975

println(name) // Print the value of name

println(birthyear) // Print the value of birthyear

The difference between var and val is that variables declared with the var keyword can be changed/modified, while val variables cannot.


Variable Type

Unlike many other programming languages, variables in Kotlin do not need to be declared with a specified type (like "String" for text or "Int" for numbers, if you are familiar with those). 
To create a variable in Kotlin that should store text and another that should store a number, look at the following example:

Ex:

 var name = "John" // String (text)

val birthyear = 1975 // Int (number)

println(name) // Print the value of name

println(birthyear) // Print the value of birthyear


Kotlin is smart enough to understand that "John" is a String (text), and that 1975 is an Int (number) variable.

However, it is possible to specify the type if you insist:

Ex:

var name: String = "John" // String

 val birthyear: Int = 1975 // Int

println(name)

println(birthyear)


You can also declare a variable without assigning the value, and assign the value later. However, this is only possible when you specify the type:

Ex:                                                   Ex:

This works fine:                    This will generate an error:                                                                                                

var name: String                             var name

name = "John"                                name = "John"        

println(name)                                  println(name)

 





No comments:

Post a Comment