Published on

Android Kotlin 101: Write Your First Program

Authors

A journey of a thousand miles begins with a single step. Let's start your first Kotlin program from this Blog Post. Good luck and become a good Software Engineer!

Install IDE

Visit the link: Download Community IDE version

Main Function - Entry Point

Let's start with the following line of code and press the Run button on the left side of the main function

fun main() {
    println("Hello Kotlin!")
}

Primary Data Types

fun main() {
    val integerVariable: Int = 0
    println("Integer Variable: $integerVariable")
    val floatVariable: Float = 1.111f
    println("Float Variable: $floatVariable")
    val doubleVariable: Double = 3.14159888
    println("Double Variable: $doubleVariable")
    val longVariable: Long = 9191488142L
    println("Long Variable: $longVariable")
    val shortVariable: Short = 32767
    println("Short Variable: $shortVariable")
    val booleanVariable: Boolean = true
    println("Boolean Variable: $booleanVariable")
    val stringVariable: String = "Hello, Kotlin!"
    println("String Variable: $stringVariable")
    val charVariable: Char = 'A'
    println("Char Variable: $charVariable")
    val byteVariable: Byte = 127
    println("Byte Variable: $byteVariable")
}

Kotlin provides all the necessary Primary data types for Programmers to write their programs. You can rest assured about this.

Operators on Basic Data Types

fun main() {
    val integerVariable: Int = 28283
    val integerVariable2: Int = 168
    println("Integer Variable: $integerVariable")
    println("Integer Variable 2: $integerVariable2")
    val addedIntegerVariable: Int = integerVariable + integerVariable2
    val subtractedIntegerVariable: Int = integerVariable - integerVariable2
    val multipliedIntegerVariable: Int = integerVariable * integerVariable2
    val dividedIntegerVariable: Int = integerVariable / integerVariable2
    val remainderIntegerVariable: Int = integerVariable % integerVariable2
    println("Added: $addedIntegerVariable")
    println("Subtracted: $subtractedIntegerVariable")
    println("Multiplied: $multipliedIntegerVariable")
    println("Divided: $dividedIntegerVariable")
    println("Remainder: $remainderIntegerVariable")
} // Similar for other data types

Kotlin provides all the calculation operators for basic data types. Try it with other data types like Float, Double, String, Byte, Short... to verify.

Operators on Bit

In reality, when developing projects, both Backend and Desktop, Mobile apps using the Kotlin language, we rarely use the Bitwise tool (Operators on Bit). However, I will still provide information for you to grasp and practice when needed.

fun main() {
    val number1 = 12
    val number2 = 25

    // Bitwise AND
    val andResult = number1 and number2
    println("Result of Bitwise AND is $andResult")

    // Bitwise OR
    val orResult = number1 or number2
    println("Result of Bitwise OR is $orResult")

    // Bitwise XOR
    val xorResult = number1 xor number2
    println("Result of Bitwise XOR is $xorResult")

    // Bitwise Inversion (NOT)
    val invResult = number1.inv()
    println("Result of Bitwise Inversion (NOT) is $invResult")

    // Bitwise Left Shift
    val leftShiftResult = number1 shl 2
    println("Result of Bitwise Left Shift is $leftShiftResult")

    // Bitwise Right Shift
    val rightShiftResult = number1 shr 2
    println("Result of Bitwise Right Shift is $rightShiftResult")
}

The operators are provided by Kotlin and used easily.

Declare Nullable, NonNullable

NULL is a concept that appears in almost all programming languages today. Handling Null checks is necessary and essential for all logic in the project.

Kotlin handles this issue by defining each variable as either Nullable or NonNullable when declared. This makes the coding process more convenient and easier. Null Check handling can be omitted if we ensure that the declared variable is a NonNullable.

A Nullable variable, when accessed, must use the ?. operator to call its internal properties. This operator will return NULL if the called variable is NULL or the called property has a NULL value.

class MyKotlinObject {
    val myKotlinProperty: String = "Hello, Kotlin!"
    val myNullKotlinProperty: String? = null
}

fun main() {
    val myNonNullKotlinObject = MyKotlinObject()
    println("myNonNullKotlinObject.myKotlinProperty: ${myNonNullKotlinObject.myKotlinProperty}")
    println("myNonNullKotlinObject.myNullKotlinProperty: ${myNonNullKotlinObject.myNullKotlinProperty}")
    val myNullKotlinObject: MyKotlinObject? = null
    println("myNullKotlinObject?.myKotlinProperty: ${myNullKotlinObject?.myKotlinProperty}")
    println("myNullKotlinObject?.myNullKotlinProperty: ${myNullKotlinObject?.myNullKotlinProperty}")
}

Example of how to use Null and NonNullable in Kotlin - Android Mastery by Danh Trần

Declare Mutable, Immutable

Kotlin is a very strict language. And that strictness is reflected in how Kotlin manages Mutable and Immutable variables in the Programmer's program.

Immutable in English means Unchangeable. That means any variable in the program declared with the Immutable type will not change its value throughout its lifetime.

To declare an Immutable variable in Kotlin, we use the keyword val before the variable name.

class MyKotlinObject {
    val myKotlinProperty: String = "Hello, Kotlin!"
    val myNullKotlinProperty: String? = null
}

fun main() {
    val myNonNullKotlinObject = MyKotlinObject()
    val myNullKotlinObject: MyKotlinObject? = null
    myNullKotlinObject = myNonNullKotlinObject // Compilation error
}

An Immutable variable can only be declared once and never reassigned throughout its lifetime.

In contrast to Immutable, Kotlin provides a way to declare Mutable variables to represent variables that can be reassigned multiple times, on different Threads, Coroutines throughout their lifetime in the program.

To declare a Mutable variable, we use the keyword var before the variable name.

class MyKotlinObject {
    val myKotlinProperty: String = "Hello, Kotlin!"
    val myNullKotlinProperty: String? = null
}

fun main() {
    var myNonNullKotlinObject: MyKotlinObject = MyKotlinObject()
    var myNullKotlinObject: MyKotlinObject? = null
    myNullKotlinObject = myNonNullKotlinObject
    myNonNullKotlinObject = MyKotlinObject()
}

When a Mutable variable is declared, it will be freely assigned new values ​​that match the declared data type throughout its lifetime in the program.

class MyKotlinObject {
    val myKotlinProperty: String = "Hello, Kotlin!"
    val myNullKotlinProperty: String? = null
}

fun main() {
    var myNonNullKotlinObject: MyKotlinObject = MyKotlinObject()
    var myNullKotlinObject: MyKotlinObject? = null
    myNonNullKotlinObject = myNullKotlinObject // Compile Error
}

The program will not compile if you try to assign a Mutable NonNullable variable to a Nullable variable

Conditional Statements, Loops in Kotlin

Similar to other programming languages. Kotlin provides tools for programmers to easily build Logic for their programs. Moreover, in Kotlin, we have much more convenient shorthand syntax.

fun main() {
    // readLine() is used to read input from the user
    val number: Int = readlnOrNull()?.toIntOrNull() ?: 0

    println("Simple if statement")
    if (number > 5) {
        println("$number is greater than 5")
    } else {
        println("$number is not greater than 5")
    }

    println("Advanced if statement")
    val checkNumberString = if (number > 5) {
        "$number is greater than 5"
    } else {
        "$number is not greater than 5"
    }

    // out standing if
    println(
        if (number > 5) {
            "$number is greater than 5"
        } else {
            "$number is not greater than 5"
        }
    )
}

Example of how to use if else in Kotlin - Android Mastery

fun main() {
    println("Enter the start value:")
    val start = readLine()?.toIntOrNull()
    println("Enter the end value:")
    val end = readLine()?.toIntOrNull()

    if (start != null && end != null && start  println("The object is a String. Value: $obj")
        is Int -> println("The object is an Integer. Value: $obj")
        else -> println("The object is of an unknown type.")
    }

    // Advanced when
    val ret = when (obj) {
        is String -> "The object is a String. Value: $obj"
        is Int -> "The object is an Integer. Value: $obj"
        else -> "The object is of an unknown type."
    }
}

Example of how to use when condition in Kotlin - Android Mastery

Declare functions in Kotlin

A function is an indispensable element in Kotlin. The Kotlin programming language provides us with many ways to declare and use functions flexibly.

fun addNumbers(num1: Int, num2: Int): Int {
    return num1 + num2
}

fun main() {
    val sum = addNumbers(5, 3)
    println("The sum is: $sum")
}

The simplest way to declare a function in Kotlin - Android Mastery

fun outerFunction() {
    fun innerFunction() {
        println("This is the inner function.")
    }

    println("This is the outer function.")
    innerFunction()
}

fun main() {
    outerFunction()
}

How to declare an inner function in Kotlin - Android Mastery

val multiply = { num1: Int, num2: Int -> num1 * num2 }

fun main() {
    val result = multiply(5, 3)
    println("The result is: $result")
}

How to declare a function as a Lambda Expression in Kotlin (A concise way of writing, used by many programmers) - Android Mastery

Object-Oriented in Kotlin

Object-oriented is a basic topic in programming. Here, I mean Object-oriented is a programming method, we can do object-oriented programming with any language. However, some languages ​​will support object-oriented programming more strongly than others. For example, here are Kotlin, C++, C#

Kotlin supports Object-Oriented programming with full features: Class, Interface, Inheritance, Polymorphism declaration. In addition, Kotlin also supports its own unique features such as data class, sealed class, Object, Enum class

Refer to the code snippets below

enum class Direction(val direction: String) {
    LEFT("LEFT"),
    RIGHT("RIGHT"),
    FORWARD("FORWARD"),
    BACKWARD("BACKWARD"),
    STOP("STOP")
}
interface Drivable {
    fun drive(direction: Direction)
}
interface Movable {
    fun speedUp()
    fun speedDown()
}
class Car : Drivable, Movable {

    private var speed: Int = 0

    companion object {
        const val MAX_SPEED = 60
        const val MIN_SPEED = 0
    }

    override fun drive(direction: Direction) {
        println("Driving the car turn $direction")
    }

    override fun speedUp() {
        speed++
        if (speed > MAX_SPEED) {
            speed = MAX_SPEED
        }
        println("Speeding up the car $speed")
    }

    override fun speedDown() {
        speed--
        if (speed  "Constant: ${expr2.number}"
        is Expr.Sum -> "Sum: ${expr2.e1} + ${expr2.e2}"
        Expr.NotANumber -> "Not a number"
    }

    println(result)
}

Example of how to use data class and sealed class in Kotlin

Extension Function in Kotlin

Extension function is a very useful and powerful feature that Kotlin provides.

Kotlin's Extension function feature supports programmers to extend the logic of a Class and reuse them effectively without having to inherit that class.

The limit of Extension function is that it cannot access private variables of the Class. Because the nature of Extension function is a static function, written concisely for us to easily use and Debug.

fun String.countVowels(): Int {
    var count = 0
    for (char in this) {
        if (char in "aeiouAEIOU") {
            count++
        }
    }
    return count
}

fun main() {
    val word = "Hello"
    println("The word '$word' has ${word.countVowels()} vowel(s).")
}

How to declare and use Extension Function - Android Mastery

Scope Function

Scope Function is a type of Extension function, supporting shorthand methods when manipulating a Kotlin Object.

data class Person(var name: String, var age: Int = 0, var city: String = "")
fun main() {
    val person = Person("John")
    println("Before update: Hello, $person")
    person.apply {
        age = 30
        city = "New York"
    }.apply {
        name = "Alice"
    } // note: apply returns the receiver object itself
    println("After update: Hello, $person")
}

How to use apply in Kotlin - Android Mastery

fun main() {
    val numbers = mutableListOf("one", "two", "three")
    numbers.also {
        it.add("four")
        println("The list elements before adding new one: $it")
    }.add("five")
    // Note: also() takes the receiver itself and returns the receiver object
    // Note: add() returns Unit
    println("The list elements after adding new one: $numbers")
}

How to use also in Kotlin - Android Mastery

fun main() {
    val listWithNulls: List = listOf("Kotlin", null)
    for (item in listWithNulls) {
        val res = item?.let {
            println(it)
            "Printed item"
        } ?: "Null item"
        // Note: let returns the last statement in the block
        println("Result: $res")
    }
}

How to use let in Kotlin - Android Mastery

Understanding and using lateinit var, val by lazy

lateinit is a Kotlin keyword to notify the compiler that the variable declared with the lateinit prefix will be initialized at a later time in the program.

Variables initialized by lateinit will be mutable (i.e. must be declared with the keyword var) and are a NonNullable variable.

If the Programmer intentionally declares a lateinit variable with an Immutable declaration or with a Nullable type, the compiler will throw an error.

In the case where logic accesses a lateinit variable that has not been initialized, the program will also throw an error at this time. Because of this, we need to really understand the program's execution flow and use lateinit intelligently and effectively.

class User {
    lateinit var address: String
    fun setAddress(address: String) {
        this.address = address
    }
    fun printAddress() {
        if(::address.isInitialized) {
            println(address)
        } else {
            println("Address is not initialized yet.")
        }
    }
}

fun main() {
    val user = User()
    user.printAddress() // Prints: Address is not initialized yet.
    user.setAddress("1 Le Duan St")
    user.printAddress() // Prints: 123 Main St
}

How to use lateinit

by lazy is another keyword in Kotlin. This keyword informs the compiler that the variable declared with by lazy has not been initialized when the program starts, instead the value of the variable will be initialized on the first access to that variable.

The variable declared by by lazy can be NonNullable, or it can also be Nullable

However, by lazy must be an Immutable, which means that throughout the variable's lifetime it only carries one unique value, which is the value initialized on the first access.

class Person {
    val name: String by lazy {
        println("Initializing name...")
        "Dan Tech 0xFF"
    }
}

fun main() {
    val person = Person()
    println(person.name) // This will print "Initializing name..." then "Dan Tech 0xFF"
}

How to use val by lazy