What is Variable in Kotlin

Variables are nothing but labels, which are given to a memory location. As variables are written in human-readable language so it is easier to access memory address using them

This memory location could have some values inside, which we are not sure of, any/no value could be there.

variables-kotlin

In layman terms, In the above image, I have given some address or a location for each bucket, now for a moment sake close your eyes and tell the bucket location of the big Kitten. I am not crazy, so please do give a try.

Unless you memorize you cannot guess or remember the locations, am I right ?, Yes.

Now let's provide some unique names to the each of the buckets, and let's try to remember/ guess it.

In the below image, I have given some names to each bucket and which indirectly points to the bucket location

variables-location-labelled-kotlin

Now I have labeled the buckets, could you try to guess the big cat (tongue out cat) label. Yes, it is possible as we have to guess the label, and the big cat bucket label is angryCat.

And this label represents the bucket location/address

Lets' get back to technical, All the values(kittens) in programming languages are stored in a place called memory(bucket), and this memory is made of series of cells, and each cell has a unique address in your computer.

The address of these cells are in a hexadecimal format like 0x7ff9c05f, which we cannot memorize (unless you belong to Albert Einstein's family), so to make it easy we provide some name/label to the address and this name is nothing but variable.

The type of a variable defines the range of values that the variable can hold and the operations that can be done on those values.

You can declare a variable in Kotlin using var and val keywords in kotlin programming language

// variable
var name = "karthiq"
// constant
val website = "chercher.tech"

Sample program for variables in Kotlin

fun main(args:Array<String>)
{
    // variable
    var name = "karthiq"
    // constant
    val website = "chercher.tech"
    println("the name is : " +name)
    println("the website is : " +website)
}

Any & Unit & nothing

Dynamic and Static Typing in Kotlin

Static Typing :

Static Typing is nothing but the types of variables is declared explicitly while declaring the variables in the program.

In Some Statically typed languages, you don’t explicitly set a type, but the programming language can assign a type at compile-time, then the language is still considered to be statically typed even though the programmer isn’t required to explicitly set a type.

Kotlin follows above two points while creating the variables in programs, so kotlin is a statically typed language. In kotlin, data types are specified during the declaration or during the compile time.

Java also a Statically typed language.

Dynamic Typing :

A programming language is said to be dynamically typed if the programmer doesn’t have to assign a type explicitly, and a type is assigned to the variable at run-time only not before the runtime

This means that with languages that use dynamic typing, you don’t have to decide if the variable you're creating should be a Double or a Float or a String or an Int, etc.

PHP, Python are dynamically typed languages.

Performance :

A compiled language will have better performance at run-time if it’s statically typed because the knowledge of types allows for machine code optimization.

Statically typed languages have better performance at run-time intrinsically due to not needing to check types dynamically while executing (it checks before running).

Similarly, compiled languages are faster at run time as the code has already been translated instead of needing to "interpret" translate it on the fly.

Error Finding :



Static typing catches errors early, instead of finding them during execution (especially useful for long programs).

Dynamic typing Languages catches the errors during the runtime only, so more prone to crashes

In simple terms, it is always better to check whether you have money or not while packing your bag in your home rather than checking on the railway station.

Operators in Kotlin

Variable Types in Kotlin

Variables in kotlin have belonged to only two categories

    • var : values can be changed after assignment
    • val : Once values are assigned then you cannot modify them, this is nothing but constants. If you try to re-assign the value, then you might face error like Val cannot be reassigned

Example of variables' value can be changed

fun main(args:Array<String>)
{
	// variable
	var name = "karthiq"
	println("the original name is : " +name)

	name = "chercher tech"
	println("name after modification : " +name)
}

For example, constants' value can't be changed

fun main(args:Array<String>)
{
	// variable
	val website = "chercher.tech"
	println("the original website is : " +website)

	website = "selenium-webdriver.com"
	println("website after modification : " +website)
}

But when you re using constants, you can declare the constants in one place and define/assign value to them in some other line like below.

fun main(args:Array<String>)
{
	// constant
	val website:String;
	website = "ka"
	println("the website is : " +website)
}

Sometimes people will assign values to constant based on if..else condition, to use such case you have to provide the data type explicitly.

fun main(args:Array<String>)
{
	// constant
	val movie:String;
	var numberOfArtists = 20;

	if(numberOfArtists < 30){
		movie = "harry Potter"
	}else{
		movie = "Lord of the Rings"
	}

	println("the movie is : " +movie)
}

Mutable Variables in Kotlin :

Mutable Variables are something whose values we can change as we wish, in kotlin all the variables which are created using var are Mutable.

ImMutable Variables in Kotlin :

Once we assign a value to variables then we cannot change their value or re-assign their value, these are called as Immutable variables and the values created by val are immutable.



Smart cast Operator [as?] in Kotlin

Data Types in Kotlin

Data Types are used to categorize values in kotlin, based on the data type functions will be available on them to perform some operations.

It is as simple as, TV, radio, Bulb just think of operations we perform on these or they perform. Similar to them every data types restricted to perform some operation in kotlin based on the operations they have categorized them.

Everything is object in Kotlin, there is no such thing as primary data types.

Java and other languages provided data types called primitive data types, but when we want to perform some complex operation or to use some complex functions o the primitive data we must convert them into objects using wrapper classes.

To reduce such effort, Kotlin kicked their butt and sent them out of kotlin programming language, so kotlin has only objects

Data Types Present in the Kotlin :

datatypes-kotlin

  • Boolean
  • Character
  • Number
  • Array (discussed in another tutorial)
  • String (discussed in another tutorial)

Boolean :

Boolean values are understood as "yes or no", "on or off", "true or false." We usually write this data into computer memory of 1 byte or 1-word size where we might refer to its value as 0x0 and 0x1.

The primary purpose of the boolean value is to make a decision, i.e based on the conditions of the boolean value decides the flow of the program

Kotlin boolean values can hold either true or false

fun main(args : Array<String>) {
	val flag: Boolean
	flag = true
	println(flag)

	if(flag){
		println("flag value true redirected me here")
	}else{
		println("flag value false sent me here")
	}
}

Character :

To represent a character in Kotlin, a character could be any single letter. Char types are used, Unlike Java, Char types cannot be treated as numbers. I mean characters in kotlin doesn't represent ASCII values

fun main(args : Array<String>) {
	val letter: Char
	letter = 'c'
	println(letter)
}

In Java, you could write something like below for characters values and the output would be

// java code
public static void main(String [] args){
	char a = 77;
	System.out.println(a);
}

//output would be the character which represent ascii value 77
M

You cannot do the same with respect to Kotlin because a character is an object in kotlin

fun main(args : Array<String>) {
	val letter: Char
	letter = 77
	println(letter)
}

Number :

Number data type represents a numeric system in Kotlin, number data types are divided into six categories.



Full Numbers

    • Byte : Basic unit in the computer is bit, 8 bit makes up a byte.

      A Byte data type can have values from -128 to 127 (this number is calculated keeping the base as 2 and power as bit value, I mean, 2 power 8 => 128).

      Kotlin will throw an error if you try to store more than 127 value in this type. This type is used to store the memory, as long as the program takes less memory it runs faster
val myByte: Byte = 14
    • Short : Contains 16 bits and it can contain values between -32768 to 32767
val myShort: Short = 200
    • Int : Int contains 32 bits, it can have a value from -2power31 to 2power31 – 1. Kotlin considers this Int data type as default data type if the user doesn't specify one
val myInt:Int = 1400
    • Long : Long Contains 64 bits, We will use this when we have some bigger values to store in programs, it can have a value from -2power62 to 2power62 – 1.
// 'L' is used to specify a long value
val myLong: Long = 1090L

Decimal Numbers

    • Float : Floats stores decimal values in Kotlin, contains 32 bit with 32-bit precession
// 'f' or 'F' represents a Float
val myFloat: Float = 1236.78f
    • Double : Double contains a decimal value with more precision, it contains 64 bit and it can contain 64bit precision
val myDouble: Double = 33665.4988

Complete program for data types, (no output as there is nothing outputted)

fun main(args:Array<String>)
{
	// Kotlin Number
	val myByte: Byte = 10
	val myShort: Short = 200
	val myInt: Int = 1400
	// 'L' is used to specify a long value
	val myLong: Long = 1090L
	// decimal values
	// 'f' or 'F' represents a Float
	val myFloat: Float = 1236.78f
	val myDouble: Double = 33665.4988
}



For Loop and types in Kotlin

Type inference in Kotlin

Type Inference in Kotlin is nothing but finding the data type of a variable based on its usage i.e based on its context.

Kotlin finds the data types during the compile-time if the user has not provided the data type during declaration.

Please do remember that type is inferred during compile time not during run time, which makes Kotlin as Statically typed language

In the below example, I have not provided the type for the firstRank but I did provide a type for secondRank as Int

fun main(args:Array<String>)
{
	var firstRank = 30 // no type is provided
	var secondRank:Int = 20 // type is provided

	// type will be decided by the compiler based on the operations
	var total = firstRank + secondRank
	println("Total is : " +total)

	println("Below will check whether compiler assigned Type is Int not")
	println(firstRank is Int)
}
In the above program, Compiler will assign Int data type to firstRank and to total, similar to this compiler will assign a data type to all the object types in Kotlin.

Type declaration becomes mandatory if you’re not initializing the variable at the time of declaration

var name   // Error: The variable must either have a Type annotation or be initialized
name =  "chercher tech"

The above variable declaration fails because Kotlin has no way to infer the type of the variable without an initializer expression.

When you do not initialize variable, then you must explicitly specify the type of the variable

var name: String   // Works
name = "chercher tech"

//this also will work fine
var site="chercher tech"



Local Functions in Kotlin

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions