What You'll Learn

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:

  1. Null safety
  2. Concise syntax
  3. More modern features.

Android studio is the official Integrated Development Environment (IDE) for Android app development.

  1. A flexible Gradle-based build system
  2. A fast and feature-rich emulator
  3. A unified environment where you can develop for all Android devices
  4. Live Edit to update composables in emulators and physical devices in real time
  5. Code templates and GitHub integration to help you build common app features and import sample code
  6. Extensive testing tools and frameworks
  7. Lint tools to catch performance, usability, version compatibility, and other problems

Download Android Studio

Download Here

For today's lab, we're going to introduce Kotlin in a practical way. Create a new project by following the steps below.

  1. Open Android Studio
  2. Create a new project Container Image
  3. Select "No Activity"

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

  1. Name the project "COMP3606Lab1"

Container Image

5.Press finish after the pre-requisites are finished downloading

  1. Create a new file called "lab1.kt"

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:

  1. Functions are declared using the fun keyword
  2. The name of the function and a pair of parenthesis goes immediately after the fun keyword
  3. Parameters are declared inside the parenthesis and they follow the syntax 'variable name' : 'variable type'
  4. If a function returns a value, it's return type is specified by placing a colon after the function name and specifying the return type
  5. Code in a pair of braces define the body of the function.
# 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")
}

Syntax Notes

  1. Like javascript, semicolons aren't used in Kotlin

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

Variable types

The list below is a non-exhaustive list of variable types in Kotlin

Numbers

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

Boolean

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

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')

String

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

If statement

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")
}

For

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 / Do-While

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!

Nullable Variables

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)

Exercise 1: Sum of Two Numbers

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.

Exercise 2: Area of a Rectangle

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.

Exercise 3: Greeting Message

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.

Exercise 4: Convert Temperature

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.

Exercise 5: Maximum of Three Numbers

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.

Exercise 6: Factorial Calculation

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.

Exercise 7: Even or Odd

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.

Exercise 8: Simple Interest Calculation

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.

Exercise 9: Check Palindrome

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".

Exercise 10: Leap Year Checker

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)
}