Here are the objectives of this lab:
Kotlin is a modern programming language used for Android development. It's fully interoperable with Java and provides a more concise syntax.
Kotlin has numerous advantages over Java such as:
Android studio is the official Integrated Development Environment (IDE) for Android app development.
For today's lab, we're going to introduce Kotlin in a practical way. Create a new project by following the steps below.

Since today's lab will be an introduction to Kotlin rather than an Android App lab, select No Activity 

5.Press finish after the pre-requisites are finished downloading
Today's lab session is just a quick crash course on Kotlin. The objective is to introduce you to Kotlin as a language and the relevant syntax to get you started.
You should be able to recall from previous courses that a function is a block of code that is executed to perform a certain task. Functions can accept parameters as input and can return values as outputs.
Functions in kotlin follow the syntax below:
fun keyword'variable name' : 'variable type'# A function that sums 2 numbers and returns the result
fun sum(a: Int, b: Int): Int {
return a + b
}
As a programming language, a special function main can be defined as the entrypoint for a file. (This is NOT applicable to Android programming as we'd see in later labs)
fun main(){
println("Hello World")
}
In Kotlin, you declare a variable starting with a keyword, val or var, followed by the name of the variable.
Use the val keyword to declare variables that are assigned a value only once. These are immutable, read-only local variables that can't be reassigned a different value after initialization:
val x: Int = 5
println(x) // 5
Use the var keyword to declare variables that can be reassigned. These are mutable variables, and you can change their values after initialization:
// Declares the variable x and initializes it with the value of 5
var x: Int = 5
// Reassigns a new value of 6 to the variable x
x += 1
println(x) // 6
The list below is a non-exhaustive list of variable types in Kotlin
Type | Size (bits) | Min value | Max value |
Byte | 8 | -128 | 127 |
Short | 16 | -32768 | 32767 |
Int | 32 | -2,147,483,648 | 2,147,483,647 |
Long | 64 | -9,223,372,036,854,775,808 | 9,223,372,036,854,775,807 |
The Boolean type refers to a boolean variable and can support many operations
Built-in operations on booleans include:
|| – disjunction (logical OR)
&& – conjunction (logical AND)
! – negation (logical NOT)
val myTrue: Boolean = true
val myFalse: Boolean = false
val boolNull: Boolean? = null
println(myTrue || myFalse)
// true
println(myTrue && myFalse)
// false
println(!myTrue)
// false
println(boolNull)
// null
Characters are represented by the type Char. Character literals go in single quotes
val aChar: Char = 'a'
println(aChar)
println('\n') // Prints an extra newline character
println('\uFF00')
Strings in Kotlin are represented by the type String.
val str = "abcd 123"
Elements of a string are characters that you can access via the indexing operation: s[i]. You can iterate over these characters with a for loop:
for (c in str) {
println(c)
}
Strings are immutable. Once you initialize a string, you can't change its value or assign a new value to it. All operations that transform strings return their results in a new String object, leaving the original string unchanged:
val str = "abcd"
// Creates and prints a new String object
println(str.uppercase())
// ABCD
// The original string remains the same
println(str)
// abcd
The if statement follows the same syntax as other languages you may be familiar with.
if (condition){
// Block to be executed if true
} else {
// Block to be executed if false
}
e.g Determine if a number is even
val num = 5
if (num % 2 == 0){
println("Number is even")
} else {
println("Number is odd")
}
The for loop iterates through anything that provides an iterator. This is equivalent to the foreach loop in languages like C#. The syntax of for is the following:
for (item in collection) print(item)
The body of for can be a block.
for (item: Int in ints) {
// ...
}
To iterate over a range of numbers, use a range expression:
for (i in 1..3) {
println(i)
}
for (i in 6 downTo 0 step 2) {
println(i)
}
while and do-while loops execute their body continuously while their condition is satisfied. The difference between them is the condition checking time:
while checks the condition and, if it's satisfied, executes the body and then returns to the condition check.
do-while executes the body and then checks the condition. If it's satisfied, the loop repeats. So, the body of do-while executes at least once regardless of the condition.
while (x > 0) {
x--
}
do {
val y = retrieveData()
} while (y != null) // y is visible here!
Kotlin is a type safe language. This means that If a variable type is declared, the variable cannot have a null value.
var x: Int
print(x)
// Above results in an error because x must be initialized
To declare a variable as one being able to hold a null value, place a questionmark after the variable type.
var x: Int? = null
println(x)
x = 5
println(x)
Write a Kotlin function sum(a: Int, b: Int): Int that takes two integers as parameters and returns their sum. Test the function with different values.
Create a function areaOfRectangle(length: Double, width: Double): Double that calculates and returns the area of a rectangle. Declare two variables length and width, and use them to call the function.
Write a function greet(name: String = "World") that prints a greeting message. The function should use a default argument if no name is provided. Test the function with and without passing a name.
Implement a function convertToFahrenheit(celsius: Double): Double that converts a temperature from Celsius to Fahrenheit using the formula: F = C * 9/5 + 32. Test the function with various temperature values.
Write a function maxOfThree(a: Int, b: Int, c: Int): Int that returns the maximum of three numbers. Declare three variables and use them to call the function.
Create a function factorial(n: Int): Int that calculates the factorial of a given number n. Use a loop or recursion to implement this function.
Write a function isEven(number: Int): Boolean that returns true if a given number is even and false if it is odd. Test the function with different integer values.
Implement a function calculateInterest(principal: Double, rate: Double, time: Int): Double that calculates the simple interest using the formula: Interest = (Principal * Rate * Time) / 100. Use variables to store the principal amount, rate, and time, and pass them to the function.
Write a function isPalindrome(word: String): Boolean that checks whether a given string is a palindrome (reads the same backward as forward). Test the function with words like "madam" and "hello".
Create a function isLeapYear(year: Int): Boolean that returns true if a given year is a leap year and false otherwise. A year is a leap year if it is divisible by 4 but not divisible by 100, unless it is also divisible by 400.
fun main(){
// println(sum(5,5))
// print(areaOfRectangle(5.0,5.0))
// greet()
// greet("Kwasi")
// println(convertToFahrenheit(40.0))
// println(maxOfThree(1,2,3))
// println(factorial(4))
// println(isEven(5))
// println(isEven(6))
println(isPalindrome("ejkrnjkerke"))
println(isPalindrome("racecar"))
}
fun sum(a: Int, b: Int,): Int {
return a + b
}
fun areaOfRectangle(length: Double, width:Double):Double{
return length * width
}
fun greet(name: String="world"){
println("Hello ${name}")
}
fun convertToFahrenheit(celcius: Double):Double {
return (celcius * 9/5) + 32
}
fun maxOfThree(a: Int, b: Int, c: Int): Int{
return if (a > b && a > c){
a
} else if (b > a && b > c){
b
} else {
c
}
}
fun factorial(n: Int): Int{
var fact =1
for (i in 1..n)
fact *= i
return fact
}
fun isEven(number: Int): Boolean{
return number%2==0
}
fun calculateInterest(principal: Double, rate: Double, time: Int): Double{
return (principal * rate * time) / 100
}
fun isPalindrome(word: String): Boolean{
var start : Int = 0
var end: Int = word.length - 1
while (start < end){
if (word[start] != word[end]){
return false
}
start++
end--
}
return true
}
fun isLeapYear(year: Int): Boolean{
return (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0)
}