Basic Kotlin 01
Basic Kotlin 01
Basic Kotlin 01
b. Safe
This language avoids entire classes of errors such as null pointer exceptions.
+ Java code:
https://onlinegdb.com/weDlUYggk
+ Kotlin code:
https://onlinegdb.com/1h8HRJTfW
Note: You must declare explicitly if a value may be null.
c. Interoperable
Java and Kotlin are 100% compatible. You can also use any existing library on the
JVM. You can use both languages in the same project. You can convert java code into
Kotlin and vice-versa.
For example, Both code has meaning.
+ Java code:
https://onlinegdb.com/XMwBiHG0-
+ Kotlin code:
https://onlinegdb.com/TTxoj7ENe
d. Tool-friendly
You can use any Java IDE to do programming in Kotlin. You can use IntelliJ, Android
Studio or Eclipse etc. to develop application using Kotlin.
1
VNDat
Kotlin
2. Variables Declaration
A kotlin variable is name given to memory location so that we can manipulate the data
within it in a program.
Each kotlin variable has a specific data type that determines the size and layout of the
variable’s memory.
The name of the kotlin variables can be composed of letters, digits and the underscore
character.
2
VNDat
Kotlin
+ Byte: this data type can have values from -128 to 127.
+ Short: it can have value from -32768 to 32767.
+ Int: it can have value from -2^31 to 2^31–1.
+ Long: it can have value from -2^63 to 2^63–1.
ex: var a:Long = 10L
+ Double
ex: var a:Double = 3.8
+ Float
ex: var a:Float = 3.8F
3
VNDat
Kotlin
* toInt(): Int
* toLong(): Long
* toFloat(): Float
* toDouble(): Double
* toChar(): Char
ex:
fun main(args: Array<String>) {
var numb: Number = 60.0
print("Number is $numb \n")
println(numb::class.java.typeName)
var numbByte = numb.toByte()
print("Number in byte is $numbByte\n")
println(numbByte::class.java.typeName)
}
3.4. Arrays Data Type: An array is a container that holds value of single type. For
example, an array of Int that holds 100 integer values, an array of Float that holds 58
floating point values etc.
4
VNDat
Kotlin
ex2:
val text = """
This is
Apple
"""
ex2:
fun main(args: Array<String>) {
var a:Int? = null
var b:Int? = null
5
VNDat
Kotlin
print("Input a:")
a = readLine()!!.toInt()
print("Input b:")
b = readLine()!!.toInt()
print("Sum : $a + $b = ${a+b}")
}
ex3:
fun main(args: Array<String>) {
var (a, b) = readLine()!!.split(' ')
println(a.toInt() + b.toInt())
}
ex4:
fun main(args: Array<String>) {
var (a, b) = readLine()!!.split(' ').map(String::toInt)
println(a + b)
}
5. Operators in Kotlin
5.1. Arithmetic operator: Arithmetic operators in Kotlin are used to carry out the basic
mathematical operations like addition, subtraction, multiplication, division and modulus.
6
VNDat
Kotlin
5.2. Comparison operator: Comparison operators in Kotlin are used to compare variables.
The comparison operators return either true or false, based on the result of the comparison.
7
VNDat
Kotlin
8
VNDat
Kotlin
5.7. Miscellaneous Operators: Kotlin also supports some more miscellaneous operators.
a. Nullable operator (?)
Kotlin doesn't allow a field to be null by default. To make a field nullable, we need to
assign ? operator.
ex:
var message: String = null // Error
var nullableMessage: String? = null // No error
b. The !! operator
The null pointer assertion operator(!!) will convert any value to non-null type and
throws an exception if the value is null.
ex:
val message: String? = null
println(message!!.length)
=> Note: This code will not throw any error during compile time but it will throw error at
runtime. This operator is not preferred to use.
c. Elvis operator
The Elvis operator in Kotlin is used to assign some other value if the reference is null.
ex:
var message: String? = null
println(message?:"Message is null")
message = "Hello World"
println(message?:"Message is null")
Output:
Message is null
Hello World
6. Kotlin Comments
6.1. Single line comment
ex:
// This is a comment
println("Enter string: ") // Enter a string here
var inputString = readLine()
println("Input in string format is: $inputString") // Input is printed here
9
VNDat
Kotlin
10
VNDat
Kotlin
}
else{
"Sorry! You failed"
}
println(result)
}
Here, based on the condition, the value will be returned from the if-else block and will
be assigned to the result variable.
Note: While using the if-else as an expression, it is compulsory to have an else block
with if block.
11
VNDat
Kotlin
8. When Expression
Consider a situation when you have large number of conditions to check. Though you can
use if..else if expression to handle the situation, but Kotlin provides when expression to
handle the situation in nicer way.
Kotlin when expression is similar to the switch statement in C, C++ and Java. Kotlin when
can be used either as an expression or as a statement.
Ex1: using when expression form
fun main(args: Array<String>) {
val day = 2
val result = when (day) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
6 -> "Saturday"
7 -> "Sunday"
else -> "Invalid day."
}
12
VNDat
Kotlin
println(result)
}
13
VNDat
Kotlin
when (day) {
1 -> {
println("First day of the week")
println("Monday")
}
2 -> {
println("Second day of the week")
println("Tuesday")
}
3 -> {
println("Third day of the week")
println("Wednesday")
}
4 -> println("Thursday")
5 -> println("Friday")
6 -> println("Saturday")
7 -> println("Sunday")
else -> println("Invalid day.")
}
}
14
VNDat
Kotlin
In Kotlin, you can use for loop to iterate through following things:
+ Range
+ Array
+ String
+ Collection
Ex2:
fun main(args: Array<String>) {
for (item in 6..1) print(item)
}
Ex3:
fun main(args: Array<String>) {
for (item in 6 downTo 1) print(item)
}
Ex4:
fun main(args: Array<String>) {
for (i in 1..6 step 2) print(i)
}
15
VNDat
Kotlin
Ex5:
fun main(args: Array<String>) {
for (i in 6 downTo 1 step 2) print(i)
}
Ex:
fun main(args: Array<String>) {
var nameList = arrayOf("Xuan", "Ha", "Thu", "Dong")
for (name in nameList)
print(name + " ")
}
Ex:
fun main(args: Array<String>) {
var nameList = arrayOf("Xuan", "Ha", "Thu", "Dong")
for (index in nameList.indices) {
println(nameList[index])
}
}
16
VNDat
Kotlin
Ex:
fun main(args:Array<String>) {
var nameList = arrayOf("Xuan", "Ha", "Thu", "Dong")
for ((index,value) in nameList.withIndex()) {
println("$index - $value")
}
}
Ex:
fun main(args:Array<String>) {
var name = "Hello World"
for (letter in name) {
print(letter + " ")
}
}
Ex:
fun main(args:Array<String>) {
var name = "Hello World"
for (index in name.indices) {
print(name[index] + " ")
}
}
17
VNDat
Kotlin
Ex:
fun main(args:Array<String>) {
var name = "Hello World"
for ((index, value) in name.withIndex()) {
println("$index => $value ")
}
}
Syntax:
while (condition) {
// body of the loop
}
18
VNDat
Kotlin
Ex1:
fun main(args:Array<String>) {
var i = 5;
while (i > 0) {
println(i)
i--
}
}
Ex2:
fun main(args:Array<String>) {
var index = 1
while(index <= 5) {
println(index * index)
index++
}
}
Ex3:
fun main(args:Array<String>) {
val nameList = arrayOf("Xuan", "Ha", "Thu", "Dong")
var index = 0;
while (index < nameList.size) {
println(nameList[index])
index++;
}
}
11. Do...while Loop in Kotlin
The loop will always be executed at least once, even if the condition is false, because
the code block is executed before the condition is tested.
19
VNDat
Kotlin
Syntax:
do{
// body of the loop
}while( condition )
Ex1:
fun main(args:Array<String>) {
var i = 5;
do{
println(i)
i--
}while(i > 0)
}
Ex2:
fun main(args:Array<String>) {
var i = 10
do {
println("Hello $i")
i -= 1
} while (i > 0)
}
Syntax:
Let's check the syntax to terminate various types of loop to come out of them:
// Using break in for loop
for (...) {
if(test){
break
}
}
20
VNDat
Kotlin
=> If test expression is evaluated to true, break statment is executed which terminates the
loop and program continues to execute just after the loop statment.
Ex:
fun main(args:Array<String>) {
var i = 0;
while (i++ < 100) {
println(i)
if( i == 3 ){
break
}
}
}
Kotlin labeled break statement is used to terminate the specific loop. This is done by
using break expression with @ sign followed by label name (break@LabelName).
Ex:
fun main(args:Array<String>) {
outerLoop@ for (i in 1..3) {
innerLoop@ for (j in 1..3) {
println("i = $i and j = $j")
if (i == 2){
break@outerLoop
}
}
}
}
21
VNDat
Kotlin
Output:
i = 1 and j = 1
i = 1 and j = 2
i = 1 and j = 3
i = 2 and j = 1
Ex:
fun main(args:Array<String>) {
var i = 0;
while (i++ < 6) {
if( i == 3 ){
continue
}
println(i)
}
22
VNDat
Kotlin
Output:
i = 1 and j = 1
i = 1 and j = 2
i = 1 and j = 3
i = 3 and j = 1
i = 3 and j = 2
i = 3 and j = 3
23
VNDat
Kotlin
24
VNDat
Kotlin
25
VNDat
Kotlin
26
VNDat