Kotlin is a JVM language. The bytecode generated by kotlin compiler is interpreted by JVM(Java Virtual Machine).Therefore, Java JDK should be installed on the machine. A least supported version of Java JDK should be Java 6.
Requirements: Any OS(Windows, Linux or Mac OS) capable of running the latest version of Java.
Filename extension: .kt,.kts
val
.In Java, it is equivalent to keyword final
. val immutableX=3 // `Int` data type is automatically inferred
val y: Int=10 // immediate assignment
val z: Int // Type required when no initializer is provided
z=5 // deferred assignment
var x=5 // `Int` data type is automatically inferred
x +=1
// This is an single line comment
// This is also called end-of-line comments
/* This is a multiple line comment
or it is also called block comments. */
Block Comments can be nested. var x=5
// simple name in template:
val s1="x is $a"
If we print the value of s1 then output will be x is 5
// between curly brackets we can call function or perform any expression:
val s2="${s1.replace("is", "was")}, but now is ${x+2}"
output if we print s2 is x was 5,but now is 7
fun multiply(x: Int, y: Int): Int{
return x + y
}
To form a function with expression body and inferred return type fun multiply(x: Int, y: Int)=x * y
fun displayMultiply(x: Int, y: Int): Unit{
println("multiplication of $x and $y is ${x + y}")
}
'Unit; can be omitted fun displayMultiply(x: Int, y: Int){
println("multiplication of $x and $y is ${x + y}")
}
fun maxOf(x: Int, y: Int): Int{
if (x > y){
return x
}else{
return y
}
}
We can also use '=' to write a shoter function as fun maxOf(x: Int, y: Int)=if(x > y) x else y
when
statement in kotlin when (a){
1 -> print("a==1")
2 -> print("a==2")
else ->{// block Statement
print("a is neither 1 nor 2")
}
}
val arrayList=listOf("one", "two", "three","four","five")
for (item in arrayList){
println(item)}
We can also use while loop for iteration val arrayList=listOf("zero","one", "two", "three","four","five")
var i=0
while (i < arrayList.size){
println("$i is ${arrayList[index]}")
index++
}