Documenting My Journey as I start Learning Kotlin

Towards the end of last year, I got an interest in learning a new programming language or library/framework for building mobile applications apart from React-Native which I had used during my first role for a couple of months. The essence of this article is to just document my Kotlin learning journey. I’m a bit inconsistent currently since I still have to improve my frontend skills that I use in my day-to-day activities.

I find learning and building projects continuously is what makes software development more refreshing. I’m more of a web developer and still have a lot of skills, especially around Javascript(core & frameworks), CSS, and technologies like Typescript that still need me up-skilling on but starting to learn Kotlin over free time might make the journey more interesting.

I started looking at Flutter and learned that one has to learn Dart programming language first before moving to build mobile app projects using Flutter and the Dart syntax is almost like that of C++ which I’m not yet familiar with. I found a few Flutter tutorials in FreeCodeCamp but a random thought came to mind when I was just getting started with Flutter to consider checking Kotlin. I saw its syntax is favorable for someone with a JavaScript background I looked into resources from Kotlin's official documentation, some courses on Udacity, and some on youtube by FreeCodeCamp. I also spoke to a developer who frequently codes with Kotlin and he shared some resources that have worked for him so far. He recommended some courses on Udacity and this youtube channel that has a Kotlin Tutorial for Beginners: The Kotlin Programming Language which he said a mentor recommended to him.

According to Kotlin’s official documentation, Kotlin is a modern but already mature programming language aimed at making developers happier. It's concise, safe, interoperable with Java and other languages, and provides many ways to reuse code between multiple platforms for effective programming.

Kotlin Basics

I have started learning Kotlin basics and just learned by coding along the last youtube tutorial I tagged the instructor recommends using the Integrated Development Environment (Intellij IDEA by Jet Brains) which I had to install and learn how to use GIT/Github on top of it as well as compiling the code after writing it and expecting an output

Steps on how to set up JDK & SDK version 17 on IntelliJ IDEA for Kotlin development

    1. Open IntelliJ IDEA and go to File > Project Structure.

      1. In the Project Structure window, select SDKs from the left menu.

      2. Click the + button to add a new SDK and select JDK.

      3. Navigate to the location of your JDK 17 installation and select it.

      4. Once the JDK is added, go to File > Project Structure again.

      5. Select Project from the left menu, and ensure that the Project SDK is set to the JDK 17 you just added.

      6. In the same window, go to the Project language level and select 17-Preview and Experimental.

      7. Click Apply and click OK to save the changes.

        Now you should be able to create a new Kotlin project and write code using JDK & SDK version 17 on IntelliJ IDEA.

        Steps on how to start a Kotlin project with a main.kt file in IntelliJ IDEA

  1. Open IntelliJ IDEA and click on "Create New Project".

  2. Select "Kotlin" as the project type and "JVM | Kotlin/JVM" as the project template.

  3. In the next window, give the project a name and select the location where you want to create the project.

  4. Click on the "Finish" button to create the project.

  5. In the project window, you'll find a file named "main.kt" under the "src" folder. This file is the entry point of your application, and it contains the main function.

  6. Open the "main.kt" file in the editor and you can start writing your code.

  7. To run the program, you can use the "Run" button on the top menu, or you can press the Shift+F10 key.

  8. IntelliJ IDEA will prompt you to choose the main class. Select "main" and click on "OK".

  9. The program will then be executed and the output will be displayed in the "Run" tab at the bottom of the screen.

Here is a sample code for the main.kt file which is the entry point of the application

fun main() {
    printLn("hello world!")
}

/* definition of keyword 
- fun: keyword for function 
- main: name of the function which is special 
*/

Kotlin: human-readable & compatible with JVM

  • Kotlin source code is designed to be human-readable and compatible with the Java Virtual Machine(JVM).

  • The Kotlin compiler takes the human-readable code written in Kotlin and transpilers it into Java bytecode which is binary code that the JVM can understand.

  • This Java bytecode can then be run on any platform that has a JVM installed e.g Windows, Mac, or Linux.

  • Advantage: This allows developers to write code in a more expressive and readable language while taking advantage of the performance and compatibility offered by the JVM.

    Writing Kotlin Code & Understanding Basic Variables, Syntax, and inBuilt Method

    Kotlin uses the camelCase naming convention i.e first word in a multi-word identifier is in lowercase and each subsequent word has its first letter capitalized. For example, "helloWorld

    • variables can be declared using the:

      • var keyword: used to declare variables and assign a value that can be reassigned
    ```kotlin
    // a value assigned to it.
    var x = 5

    // without assigning a value, and assign a value later
    var y: Int
    y = 6

    // reassign a value to a variable that has already been declared and assigned a value
    x = 7
    ```

    * `val` keyword: used to declare variables and assign a value that cannot be reassigned i.e value cannot be changed. It’s the same as `const` in Javascript


    ```kotlin
    val name: String = "Sharon Jebitok"
    ```

* Kotlin has many inbuilt methods which are available for different contexts. e.g

    * String class:


    ```kotlin
    length() // returns the number of characters in a string 
    substring(startIndex: Int, endIndex: Int) // returns a new string i.e substring of the original string, starting at the specified startIndex & ending at the specified endIndex-1.
    toLowerCase() // returns a new string with all characters in lowercase
    toUpperCase() // returns a new string with all characters in uppercase
    trim() // returns a new string with leading and trailing whitespace removed
    split(delimiter: String) // returns a list of substrings, split by the specified delimiter
    replace(oldValue: String, newValue: String) // returns a new string with all occurrences of the specified oldValue replaced with the specified newValue
    ```

    * Collection classes


    ```kotlin
    filter(predicate: (T) -> Boolean) // returns a new collection containing only elements that satisfy the specified predicate
    map(transform: (T) -> R) // returns a new collection containing the results of applying the specified transform function to each element in the original collection
    reduce(operation: (acc: R, T) -> R) // applies the specified binary operation to the elements in the collection, going left to right, and returning an accumulation of the operation
    forEach(action: (T) -> Unit) // performs the specified action on each element of the collection
    any() // returns true if at least one element in the collection satisfies the specified predicate, otherwise false
    all(predicate: (T) -> Boolean) // returns true if all elements in the collection satisfy the specified predicate, otherwise false
    ```

    * Numbers


    ```kotlin
    toInt(): // Converts a number to an integer
    toLong(): // Converts a number to a long
    toFloat(): // Converts a number to a float
    toDouble(): // Converts a number to a double
    abs(): // Returns the absolute value of a number
    round(): // Rounds a number to the nearest whole number
    ceil(): // Rounds a number up to the nearest whole number
    floor(): // Rounds a number down to the nearest whole number
    sqrt(): // Returns the square root of a number
    pow(): // Raises a number to a specified power
    ```

    * Arrays


    ```kotlin
    sort(): // sorts the elements of the array in ascending order
    slice(): // returns a subarray that starts at a specified index and has a specified length
    fill(): // fills all elements of the array with a specified value
    copyOf(): // returns a new array that is a copy of the original array
    copyOfRange(): // returns a new array that is a copy of a range of elements from the original array
    forEach() : // Iterates over array elements and perform the given action on each element
    ```

* types of numbers that can be used to represent different ranges of values in Kotlin

    * `Byte` An 8-bit signed integer. It can hold values from -128 to 127

    * `Short` A 16-bit signed integer. It can hold values from -32768 to 32767

    * `Int` A 32-bit signed integer. It can hold values from -2147483648 to 2147483647

        `Long` A 64-bit signed integer. It can hold values from -9223372036854775808 to 9223372036854775807

    * `Float` A 32-bit floating-point number. It can hold decimal values

    * `Double` A 64-bit floating-point number. It can hold decimal values and is the default type for decimal numbers in Kotlin.


    ```kotlin
    val d: Double = 3.14 //Double 
    var b: Byte = 100 // Byte
    val f: Float = 3.14f // Float
    val l: Long = 10000000000 // Long
    val i: Int = 100000 // Int
    val s: Short = 10000 // Short
    ```

* // [main.](http://main.lt)kt file with sample code of inbuilt methods & variables
fun main() {
    var fullName: String = "Sharon Jebitok"
    var age:Int = 26
//    numbers
    val myByte: Byte = 8 // 8-bit signed integer
    val myShort: Short = 16 // 16-bit signed integer
    val myInt: Int = 32 // 32-bit signed integer
    val myLong: Long = 64 // 64-bit signed integer

//    decimals
    val myFloat: Float = 32.00F // 32-bit floating point number
    val myDouble: Double = 64.00 // 64-bit floating point number

    val bigLong: Long = 1_000_000
    println(bigLong)

    val newInt = myInt.plus( other = 12)

    println(newInt)
//    println(bigLong)
//    println(myByte.toDouble()::class)
//    println(myByte.toShort()::class)
//    println(myByte.toLong()::class)
//    println(myByte.toFloat()::class)
//    println(myByte.toInt()::class)
//    println(myByte.toByte()::class)
}

Thank you for reading through my article. You can leave a comment if you’re aware of a better way to learn Kotlin or maybe you’re also getting started and need a buddy. We can also connect on Twitter or LinkedIn. I would like to acknowledge the tutorial I've been using and ChatGTP their resources have come in handy in understanding the basics and also putting together this article.

Did you find this article valuable?

Support Sharon Jebitok by becoming a sponsor. Any amount is appreciated!