[Kotlin] Introduction to Kotlin Programming Language

Date:     Updated:

Categories:

Tags:

📋 Here are the notes summarizing what I learned from the course!


Introduction to Kotlin Programming Language

Objectives:

  • Review the basics of Kotlin programming language including variables, control structures, functions, classes, and collections.
  • Set up Android Studio to use Kotlin and build apps.
  • Develop Android apps using Kotlin.

What is Kotlin?

Kotlin is a statically typed programming language for modern multiplatform applications, meaning type checking is done at compile-time. It is 100% interoperable with Java and Android.

Basic Syntax

  • Package specification should be at the top of the source file.
    package my.demo
    import java.util.*
    

Defining Functions

  • Function with two Int parameters returning Int:
    fun sum(a: Int, b: Int): Int {
        return a + b
    }
    
  • Function with an expression body and inferred return type:
    fun sum(a: Int, b: Int) = a + b
    
  • Function returning no meaningful value (Unit return type can be omitted):
    fun printSum(a: Int, b: Int) {
        println("sum of $a and $b is ${a + b}")
    }
    

Defining Variables

  • Read-only local variable:
    val a: Int = 1  // immediate assignment
    val b = 2       // `Int` type is inferred
    val c: Int      // Type required when no initializer is provided
    c = 3           // deferred assignment
    
  • Mutable variable:
    var x = 5
    x += 1
    

Using String Templates

  • Example of simple name in template and arbitrary expression in template:
    var a = 1
    val s1 = "a is $a"
    a = 2
    val s2 = "${s1.replace("is", "was")}, but now is $a"
    

Using Conditional Expressions

  • Using if as an expression:
    fun maxOf(a: Int, b: Int) = if (a > b) a else b
    

Using Nullable Values and Checking for Null

  • Function that returns a nullable Int:
    fun parseInt(str: String): Int? {
        // implementation
    }
    

Using Collections

  • Iterating over a collection and checking if it contains an object:
    val items = listOf("apple", "banana", "kiwi")
    for (item in items) {
        println(item)
    }
    when {
        "orange" in items -> println("juicy")
        "apple" in items -> println("apple is fine too")
    }
    

Classes

  • Example of a simple class:
    class Person(firstName: String, lastName: String, personAge: Int) {
        val upperCaseFirstName = firstName.toUpperCase()
        val upperCaseLastName = lastName.toUpperCase()
        var age = personAge
    
        init {
            println("Uppercase First Name = $upperCaseFirstName")
            println("Age = $age")
        }
    }
    

Data Classes

  • Example of a data class:
    data class User(val name: String, val age: Int)
    

References:




Back to Top

See other articles in Category Kotlin

Leave a comment