variables-datatypes-kotlin

What is Variables 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 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 bucket, and let's try to remember/ guess it.

In below image I have given some names to the 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 represent 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 hexa-decimal format like : 0x7ff9c05f, which we cannot memorize (unless you belong 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 the 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 languages. In kotlin, data types are specified during the declaration or during the compile time.

Java is also Statically types 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 actually 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 railway station.

Operators in Kotlin

Variable Types in Kotlin

Variables in kotlin are belong 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 for 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)
}

Example for 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 a 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?]

Data Types in Kotlin

Data Types are used to categorization of 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 a 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.

Primary purpose of the boolean value is to make decision, i.e based on the boolean values conditions decides the flow of the program

Kotlin boolean values can either hold 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, 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 character is object in kotlin


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

Number :

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

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

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

    Kotlin will throw error if you try to store more than 127 value in this type. This type is used to store the memory, as long as a program takes less memory it runs faster
  • 
    								val myByte: Byte = 14
    								

  • Short : Contains 16 bits and it can contains values between -32768 to 32767
  • 
    								val myShort: Short = 200
    								

  • Int : Int contains 32 bits, it can have value from -2power31 to 2power31 – 1. Kotlin considers this Int data type as default data type if 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 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 decimal value with more precision, it contains 64 bit and it can contains 64bit precision
  • 
    								val myDouble: Double = 33665.4988
    								

Complete program for data types, (no out put 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 user have 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 below example i have not provided the type for the firstRank but i did provided 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 above program, Compiler will assign Int data type to firstRank and to total, similar to this compiler will assign 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 donot 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

aaaaaaaaaaaaa
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Recent Addition

new tutorial Selenium Online Training : Our next online training course for Selenium with Java starts from 17th December 2018.

You can attend first 3 classes for free, the total course fee is INR 10,000

The course time would be 8.00 PM(IST) for the first three classes

If you are interested to learn, then you can join the course by sending email to chercher.tech@gmail.com

or Register below


 
Join My Facebook Group
Join Group