In this tutorial we will go through the variables usage in Kotlin though you have a knowledge of variables in various other programming languages but Kotlin has a slightly different type of initialization compared to java.

Variables are the basic requirements for any type of program.Even it might be a one page or a big enterprise software variables have their own usage and importance.

In the previous tutorial we have gone through basic usage of method and print to display a message now we will go through basic usage of variables in Kotlin.

 

String variable

Strings are mostly used variables out of all other variables if i am wrong in this assumption let me know in comment section below. so let’s see how we used them before and how we are going to use them in Kotlin

 

java:

We can directly assign a values at the time of initialization

 

Or another way of initializing a String

 

Assigning a value to it later..

 

Kotlin:

Kotlin also has the same usage of variables as the code written in Kotlin is converted to java, but declaration is different compared to that of java

  1. Var keyword is specified
  2. Name of the variable is specified
  3. Type of the variable is specified using a  ‘ : ‘

 

 

and as in the java value can be later assigned

 

or at the time of initialization as

 

That’s ok and simple but lets know further this String message can be redefined any number of times and it accepts every new message and stores replacing the previous message.

 

Static String Declaration

Now let’s see a String which cannot be redefined again and again.This is called a static way of declaring a String it has its own importance in programming world.

 

java:

try to redefine the variable let me know result in comment section

 

Kotlin:

Yes Kotlin also has static way of  declaring a variable as val

  1. Val keyword is specified for static variable
  2. Name of the variable is specified
  3. Type of the variable is specified using a  ‘ : ‘

 

 

Now try to redefine this and let me know..

 

Integer Variable

Actually after going through the above info you can declare an integer variable in same way but there is a small difference you may guess it but lets see

 

java:

 

Kotlin:

You cannot use small ‘ i ‘ here in declaring a integer variable instead use capital ‘ I ‘ as below

 

 

Static Integer Variable

 

java:

 

Kotlin:

Val is used for static declarations of variables.

 

 

 

 

 

Show Buttons
Hide Buttons
Read previous post:
Android Introduction to Kotlin

Close