A varible refers to a memory allocation that can be store data.
Variables in kotlin can be allow as like java.
In kotlin we can define varible as var or val keywords.
A varible defined by val is immutable(can't change the value )
val intvar=12; intvar=13; /* Error: val can not be change */ To define the mutable varibles we will use var keyword. var intvar=12; intvar=13; here we can change the value of intvar |
In the above line we didn't define the type of variable, we know kotlin is statically typed langugae. it will infer the type of variable from its initialization value.
In the above line the intvar type will takes as integer.
If we want to define the type of variable we will write like below
var intvar:Int =12;
If we not initialize a variable its mandatory to define the type of varibale
var k // Error : This varibale must either have a Type annonation or be initialized
k="Kotlin"
The above variable declaration throws error. If we not initalize a variblae we must supply the varible Type.
So that could be like below
var k:String
k="Kotlin"
Data Types
Kotlin has pre-defined data types like other langugaes Int, Double, Boolean, Char etc.
In Kotlin every data type behaves like Object (In java few are Object(String, Integer, Float) types and few are premitive types(int, float, double,...)
Numbers
Booleans
Bolean
val myConditaion = true
Characters
Character
val myChar='A'
Strings
Strings are immutable, that means we cannot modify a String by changing some of its elements
var myString="Kotlin, New Version"
We will see the String properties and functions indetails in Strings chapter.
Arrays
Arrays in kotlin can be defined by Array class.
We can create array object by two ways.
arrayOf() function or
Array() consturctor
var intArray= arrayOf(1,2,3,4);
create array with constructor
var consrtArray=Array(5,{i-> "a $i"});
We will see the Array properties and functions indetails in Arrays chapter.
Type Conversions
Unlike Java, Kotlin doesn't support implicit conversion
Example int cann't be assigned to long or Double
var myInt=10
var myLong:Long =myInt /* throw Error : Type missmatched required Long found Int.*/
Kotlin provided few number functions to explicit conversions