501 02 CH 1
501 02 CH 1
- 2024-25
TYBCA – SEM5 - 501-02 - Advanced Mobile Computing
In this chapter, we will use IntelliJ (developed by the same people that created Kotlin)
which is free to download from https://www.jetbrains.com/idea/download/.
Kotlin Install
Once IntelliJ is downloaded and installed, click on the New Project button to get started with
IntelliJ:
Then click on "Kotlin" in the left side menu, and enter a name for your project:
When the JDK is downloaded and installed, choose it from the select menu and then click on
the "Next" button and at last "Finish":
Now we can start working with our Kotlin project. Do not worry about all of the different buttons and functions in
IntelliJ. For now, just open the src (source) folder, and follow the same steps as in the image below, to create a
kotlin file:
Select the "File" option and add a name to your Kotlin file, for example "Main":
Next, IntelliJ will build your project, and run the Kotlin file. The output will look something like this:
Kotlin Syntax
In the previous chapter, we created a Kotlin file called Main.kt, and we used the following
code to print "Hello World" to the screen:
fun main()
{
println("Hello World")
}
The fun keyword is used to declare a function. A function is a block of code designed to
perform a particular task. In the example above, it declares the main() function.
The main() function is something you will see in every Kotlin program. This function is
used to execute code. Any code inside the main() function's curly brackets {} will be
executed.
For example, the println() function is inside the main() function, meaning that this will
be executed. The println() function is used to output/print text, and in our example it
will output "Hello World".
Good To Know: In Kotlin, code statements do not have to end with a semicolon (;) (which is
often required for other programming languages, such as Java, C++, C#, etc.).
Main Parameters
Before Kotlin version 1.3, it was required to use the main() function with parameters, like:
fun main(args : Array<String>). The example above had to be written like this to work:
Single-line Comments
Single-line comments starts with two forward slashes (//).
Any text between // and the end of the line is ignored by Kotlin (will not be executed).
This example uses a single-line comment before a line of code:
// This is a comment
println("Hello World")
Multi-line Comments
Multi-line comments start with /* and ends with */.
Any text between /* and */ will be ignored by Kotlin.
This example uses a multi-line comment (a comment block) to explain the code:
/* The code below will print the words Hello World
to the screen, and it is amazing */
println("Hello World")
1.3 Variables:
1.3.1 val vs. var, Byte, Short, Int, Long, Float, Double, Boolean, and Char.
1.3.2 String, Nullable variables
In Kotlin, every variable should be declared before it‟s used. Without declaring a variable,
an attempt to use the variable gives a syntax error. Declaration of the variable type also
decides the kind of data you are allowed to store in the memory location. In case of local
variables, the type of variable can be inferred from the initialized value.
var rollno = 55
var name = "Praveen"
println(rollno)
println(name)
Above we have the local variable rollno whose value is 55 and it‟s type is Integer because
the literal type is Int and another variable is name whose type is String. In Kotlin, variables
are declared using two types –
Immutable using val keyword
Mutable using var keyword
1. Immutable Variables –
Immutable is also called read-only variables. Hence, we cannot change the value of the
variable declared using val keyword.
val myName = "Gaurav"
myName = "Praveen" // compile time error
Note: Immutable variable is not a constant because it can be initialized with the value of a
variable. It means the value of immutable variable doesn’t need to be known at compile-
time, and if it is declared inside a construct that is called repeatedly, it can take on a
different value on each function call.
var myBirthDate = "02/12/1993"
2. Mutable Variables –
In Mutable variable we can change the value of the variable.
var myAge = 25
myAge = 26 // compiles successfully
println("My new Age is ${myAge}")
Output:
My new Age is 26
Scope of a variable – A variable exists only inside the block of code( {………….} ) where it
has been declared. You cannot access the variable outside the loop. Same variable can be
declared inside the nested loop – so if a function contains an argument x and we declare a
new variable x inside the same loop, then x inside the loop is different than the argument.
Naming Convention – Every variable should be named using lowerCamelCase.
val myBirthDate = "02/12/1994"
Integer Types
Byte
The Byte data type can store whole numbers from -128 to 127. This can be used instead of
Int or other integer types to save memory when you are certain that the value will be within
-128 and 127:
Short
The Short data type can store whole numbers from -32768 to 32767:
Int
The Int data type can store whole numbers from -2147483648 to 2147483647:
Long
The Long data type can store whole numbers from -9223372036854775807 to
9223372036854775807. This is used when Int is not large enough to store the value.
Optionally, you can end the value with an "L":
Difference Between Int and Long
A whole number is an Int as long as it is up to 2147483647. If it goes beyond that, it is
defined as Long:
fun main() {
val myNum: Double = 19.99
println(myNum)
}
Strings
The String data type is used to store a sequence of characters (text). String values must be
surrounded by double quotes:
fun main() {
val myText: String = "Hello World"
println(myText)
}
print("GeeksforGeeks - ")
print("A Computer Science portal for Geeks")
}
Output:
GeeksforGeeks
A Computer Science portal for Geeks
GeeksforGeeks - A Computer Science portal for Geeks
var a = 10
var b = 20
var c = 30L
var marks = 40.4
Kotlin Input –
Kotlin standard input is the basic operation performed to flow byte streams from input
device such as Keyboard to the main memory of the system.
You can take input from user with the help of the following function:
readline() method
Scanner class
Take input from user using readline() method –
fun main(args : Array<String>) {
print("Enter text: ")
var input = readLine()
print("You entered: $input")
}
The following helper function can be used to convert one data type into another:
toByte()
toShort()
toInt()
toLong()
toFLoat()
toDouble()
toChar()
if-else statement:
if-else statement contains two blocks of statements. „if‟ statement is used to execute the
block of code when the condition becomes true and „else‟ statement is used to execute a
block of code when the condition becomes false.
Syntax:
if(condition) {
// code to run if condition is true
}
OUTPUT:
Output:
Enter the name of heavenly body: Sun
Sun is a Star
Enter the name of heavenly body: Mars
I don't know anything about it
If none of the branch conditions are satisfied with the argument, the else branch is
executed. As an expression, the else branch is mandatory, unless the compiler can prove
that all possible cases are covered with branch conditions. If we cannot use else branch it
will give a compiler error.
Error:(6, 17) Kotlin: 'when' expression must be exhaustive, add necessary 'else' branch
Creating an array –
In Kotlin, arrays are not a native data type, but a mutable collection of similar items which
are represented by the Array class.
There are two ways to define an array in Kotlin.
1. Using the arrayOf() function
2. Using the Array constructor
for (i in 0..arrayname1.size-1)
{
print(" "+arrayname1[i])
}
println() // declaring an array using arrayOf<Int>
val arrayname2 = arrayOf<Int>(10, 20, 30, 40, 50)
for (i in 0..arrayname2.size-1)
{
print(" "+ arrayname2[i])
}
}
OUTPUT:
1 2 3 4 5
10 20 30 40 50
In the above example, we pass the size of the array as 3 and a lambda expression which
initializes the element values from 0 to 9.
for (i in theList.indices) {
println(theList[i])
}
}
Using forEach
fun main() {
val theList = listOf("one", "two", "three", "four")
theList.forEach { println(it) }
}
Size of Kotlin List
We can use size property to get the total number of elements in a list:
fun main() {
val theList = listOf("one", "two", null, "four", "five")
if(theList.isEmpty()){
println(true)
}else{
println(false)
}
}
OUTPUT:
false
Example
fun main() {
val theList = listOf("one", "two", "three", "four")
List Addition
We can use + operator to add two or more lists into a single list. This will add second list
into first list, even duplicate elements will also be added.
Example
fun main() {
val firstList = listOf("one", "two", "three")
val secondList = listOf("four", "five", "six")
val resultList = firstList + secondList
println(resultList)
}
OUTPUT:
[one, two, three, four, five, six]
List Subtraction
We can use - operator to subtract a list from another list. This operation will remove the
common elements from the first list and will return the result.
fun main() {
val firstList = listOf("one", "two", "three")
val secondList = listOf("one", "five", "six")
val resultList = firstList - secondList
println(resultList)
}
OUTPUT:
[two, three]
Slicing a List
We can obtain a sublist from a given list using slice() method which makes use of range of
the elements indices.
Example:
fun main() {
val theList = listOf("one", "two", "three", "four", "five")
val resultList = theList.slice( 2..4)
println(resultList)
}
OUTPUT:
[three, four, five]
println(resultList)
}
OUTPUT:
[one, two, four, five]
theList.add(40)
theList.add(50)
println(theList)
theList.remove(10)
theList.remove(30)
println(theList)
}
OUTPUT:
[10, 20, 30, 40, 50]
[20, 40, 50]
For Loop:
Often when you work with arrays, you need to loop through all of the elements.
To loop through array elements, use the for loop together with the in operator:
fun main()
{
val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
for (x in cars)
{
println(x)
}
}
You can loop through all kinds of arrays. In the example above, we used an array of strings.
In the example below, we loop through an array of integers:
Kotlin Ranges
With the for loop, you can also create ranges of values with "..":
fun main()
{
for(chars in 'a'..'x')
{ println(chars) }
}
Loops are handy because they save time, reduce errors, and they make code more
readable.
Continue Statement
Kotlin, continue statement is used to repeat the loop. It continues the current flow of the
program and skips the remaining code at specified condition.
The continue statement within a nested loop only affects the inner loop.
Syntax:
for(..){
//body of for above if
if(checkCondition){
4. Implicit Return:
Kotlin
fun square(x: Int) = x * x
In single-expression functions, the return keyword can be omitted, and the expression's
value is returned automatically.
Kotlin Functions
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
Functions are used to perform certain actions, and they are also known as methods.
In Kotlin, functions are declared using fun keyword. There are two types of functions
depending on whether it is available in standard library or defined by user.
1) Standard library function
2) User defined function
Call a Function
Now that you have created a function, you can execute it by calling it.
To call a function in Kotlin, write the name of the function followed by two parantheses ().
In the following example, myFunction() will print some text (the action), when it is called:
fun myFunction() {
println("I just got executed!")
}
fun main() {
myFunction()
}
Function Parameters
The following example has a function that takes a String called fname as parameter. When
the function is called, we pass along a first name, which is used inside the function to print
the full name:
fun myFunction(fname: String) {
println(fname + " Doe")
}
fun main() {
myFunction("John")
myFunction("Jane")
myFunction("George")
}
Return Values
In the examples above, we used functions to output a value. In the following example, we
will use a function to return a value and assign it to a variable.
To return a value, use the return keyword, and specify the return type after the function's
parantheses (Int in this example):
Example
A function with one Int parameter, and Int return type:
fun myFunction(x: Int): Int {
return (x + 5)
}
fun main() {
var result = myFunction(3)
println(result)
}
Example
A function with two Int parameters, and Int return type:
fun myFunction(x: Int, y: Int): Int {
return (x + y)
}
fun main() {
var result = myFunction(3, 5)
println(result)
}