What is variable?

Variable is a container type where you store your data. It has a name by which you can access this data.The data of variable can be changed and reused depending on condition or on information passed to the program.

Kotlin provides two types of variables that is immutable and mutable. An immutable variable is one whose value we cannot be changed and also known as unchangeable or read-only variable. Mutable variable can be changed we can re assign value to mutable variable

How to declare a variable in Kotlin?

In Kotlin you can declare a variable using var or val keyword . Here is an example:

var language ="Codinglance"  
val salary = 40000 

val keyword(Immutable variable)

Immutable variable in kotlin is declared using val keyword in Kotlin. in this we can not re assign value to the variable if we do then it will through an error. Lest see an example, we have declared an immutable variable Name using val keyword and later displayed the value of it.


fun main(args : Array<String>){
    /**
     * This is an immutable variable
     * also called unchangeable variable
     * or read-only variable.
     */
    val myTopic = "Immutable"
    println("My Topic is: "+myName)
}

Let’s see what happens when we try to change the value of an immutable variable?

If we try to change the value of a val variable, we will get a compilation error, let’s see an example.

fun main(args : Array<String>){
    /**
     * This is an immutable variable
     * also called unchangeable variable
     * or read-only variable.
     */
    val myTopic = "Immutable"
    myTopic="Immutable kotlin"

    println("My Topic is: "+myName)
}

output

Error:(13, 5) Kotlin: Val cannot be reassigned

Mutable variable: var keyword

In kotlin we have ability to change the value of a mutable variable. A mutable variable can be declare using var keyword . Lets see an example.

fun main(args : Array<String>){
    /**
     * This is an immutable variable
     * also called unchangeable variable
     * or read-only variable.
     */
    var myTopic = "Immutable"
    myTopic="Immutable kotlin"

    println("My Topic is: "+myName)
}

Difference between var and val

A variable declared using val keyword is immutable (read-only).After it is initialized .It cannot be reassigned –

val language = "Codinglance"  
language = "Kotlin" //Error 

For defining a mutable variable, i.e. a variable whose value can be changed, use the var keyword –

var country = "Codinglance"
country = "India" //works

Type inference

As Kotlin is a statically typed language.It can infer the type of a variable from the initializer expression.It doesn’t require you to explicitly specify the type of every variable you declare:-

val greeting = "Codinglance"  // type inferred as `String`
val year = 2021             // type inferred as `Int`

you can also explicitly specify the type of a variable, if you want to do this then you can do by –

// Explicitly defining the type of variables
val name: String = “Codinglance“
val year: Int = 2021

Must note if you’re not initializing the variable at the time of declaration then the type declaration becomes mandatory –

var language   // Error: The variable must either have a Type annotation or be initialized
language =  "Kotlin"

The above variable declaration fails because There is no way  in Kotlin to infer the type of the variable without an initializer expression. In such case, you have to explicitly specify the type of the variable –

var language: String   // Works
language = "Kotlin"

Kotlin Data Types

Data Types are used to divided a set of related values and define the operations that can be done on them.Just like other languages.Everything is an object In Kotlin. Kotlin represent some of the basic types like characters, booleans and numbers,  as primitive values at runtime to improve performance, but for end users, all of them are objects. Kotlin has predefined types like Int, Double Boolean, Char etc:-

  • Numbers
  • Boolean – True, false
  • Characters
  • Arrays
  • Strings

Numbers

They are similar to java.They can be categorised into integer and floating point types.

  • Byte:-The Byte data type can have Data Range from -128 to 127 and 8 bit Bit Width.
  • Short:-The Short data type can have Data Range from -32768 to 32767 and 16 bit Bit Width.
  • Int:-The Int data type can have Data Range from -2,147,483,648 to 2,147,483,647 and 32 bit Bit Width.
  • Long:-TheLong data type can have Data Range from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807 and 64 bit Bit Width.
  • Float:-The Float data type can have Data Range from 1.40129846432481707e-45 to 3.40282346638528860e+38 and 32 bit Bit Width.
  • Double:-The Double data type can have Data Range from 4.94065645841246544e-324 to 1.79769313486231570e+308 and 64 bit Bit Width.

Boolean

Boolean variable can be true or false.

fun main(args : Array<String>) {

    val flag = true
    println("$flag")
}

Characters

Characters are represented using the type Char. Unlike Java,You cannot assign numbers to the variable of Char data type.They are declared using single quotes like this –

val alphaChar = ‘C’
val numberChar = '9'

Arrays

Array is a collection of similar data type. In kotlin we can define array in two ways that is  using the helper function arrayOf() or the constructor Array()

Using the Array constructor –
val num = Array(3, {i-> i*1}

Primitive Arrays

As we know now, everything in Kotlin is an object. To improve performance kotlin represents some of the basic types like characters, numbers and booleans as primitive types at runtime.

To creates arrays of boxed/wrapper types The arrayOf() function is used . That is, arrayOf(1, 2, 3) which is corresponds to Java’s Integer[] array.

But, Kotlin provides a way by which we can create arrays of primitive types as well. It has  specialized classes for representing array of primitive types. Those classes can be – IntArray, DoubleArray, CharArray etc. You can create an array of primitive types using the corresponding library functions – intArrayOf(), doubleArrayOf(), charArrayOf() etc. –

val forCharArray = charArrayOf(‘A’, ‘B’, ‘C’)  // CharArray (corresponds to Java ‘char[]’)

val forIntArray = intArrayOf(2, 3, 7, 5)

Using the arrayOf() function –
val num = arrayOf(1, 2, 3, 4)   //implicit type declaration
val num = arrayOf<Int>(1, 2, 3) //explicit type declaration

Strings

Strings are represented using the String class. Strings are immutable, means you cannot modify a String by changing some of its elements.

val myString = "This is a Coadinglance"

You may also like...

0 Comments

No Comment.