Skip to main content

Kotlin Basic Syntax

Basic Syntax

kotlin syntax is somewhere similar to java but there are few changes that had made easier for developers to clean and optimize their code with ease.

Defining packages

The package specification is similar to Java which should be at the top of the source file:

 package org.project.demo
 import java.util.*
 // comment
{...}

Defining functions

Defining function in kotlin is much easier. It is also more clear to read and understand. kotlin support for inline functions, code using lambdas often runs even faster than the same code written in Java.  Some examples:

Function having two Int parameter with Int return type:
   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

Defining variables

Variables in kotlin allow, as in Java, to assign values that can then be modified and used at different points in our program. The variables can be mutable and immutable.

Immutable variables(read-only):
 // immediate assignment
 val a: Int = 0
 // `Int` type is inferred
 val b = 1
 // Type required when no initializer is provided
 val c: Int
 // deferred assignment
 c = 5

Mutable variables:
 // `Int` type is inferred
 var x = 5
 x += 1

Top-level variables:
 val PI = 3.14
 var x = 0
 fun incrementX() {
    x += 1
}

String Templates

Strings may contain template expressions, i.e pieces of code that are evaluated and whose results are concatenated into the string. A template expression starts with a dollar sign ($) and consists of either a simple name:

val x = 20
val s = "x = $x" // evaluates to "x = 20"

or any arbitrary expression in curly braces:

val i = "xyz" val str = "$i.length is ${i.length}" // evaluates to "xyz.length is 3"

Conditional expressions

fun maxOf(a: Int, b: Int): Int {
    if (a > b) {
        return a
    } else {
        return b
    }
}

if can be used as an expression as below:

fun maxOf(a: Int, b: Int) = if (a > b) a else b

Check for null

fun printProduct(arg1: String, arg2: String) {
    val x = parseInt(arg1)
    val y = parseInt(arg2)

    // Using `x * y` yields error because they may hold nulls.
    if (x != null && y != null) {
        // x and y are automatically cast to non-nullable after null check
        println(x * y)
    }
    else {
        println("either '$arg1' or '$arg2' is not a number")
    } 
}


For Loop

for loop iterates through anything that provides an iterator. This is equivalent to the  foreach  loop in languages like C#. The syntax is as follows:

for (item in collection) print(item)

To iterate through an array or a list with an index

  for (i in array.indices) {
print(array[i]) }

While Loops

while and do while works as usual.

val items = listOf("apple", "ball", "cat")
var index = 0
while (index < items.size) {
    println("item at $index is ${items[index]}")
    index++
}

When Expression

when replaces the switch operator of C-like languages. In the simplest form, it looks like this

when (x) { 1 -> print("x == 1") 2 -> print("x == 2") else -> { // Note the block print("x is neither 1 nor 2") } }

Collections

Checking if a collection contains an object using in operator:

when {
    "orange" in items -> println("juicy")
    "apple" in items -> println("apple is fine too")
}

Using lambda expressions to filter and map collections:

fruits
.filter { it.startsWith("a") }
.sortedBy { it }
.map { it.toUpperCase() }
.forEach { println(it) }

Creating basic classes and their instances

val rectangle = Rectangle(5.0, 2.0) //no 'new' keyword required
val triangle = Triangle(3.0, 4.0, 5.0)


Comments

Popular posts from this blog

Kotlin Coding Conventions

In this post, I will discuss the Kotlin coding conventions which are a lot similar to other programming languages. So without further delay lets move to our today's discussion. Source code organization Source code organization is one of the first things we need to discuss in Kotlin coding conventions . Just like in other programming languages, an organization of source code is important in Kotlin for a consistent look across all the projects. Directory structure The source files should reside in the same source root as the Java source files, and follow the same directory structure. In pure Kotlin projects, the recommended directory structure is to follow the package structure with the common root package omitted. Example: if all the code in the project is in the "org.example.kotlin" package and its sub-packages, files with the "org.example.kotlin" package should be placed directly under the source root, and files in "org.example.kotlin.foo...

Kotlin fun to learn

Kotlin is a programming language developed by JetBrains for modern multiplatform applications. It runs on the Java Virtual Machine(JVM) and also can be compiled to JavaScript code or use the Low Level Virtual Machine(LLVM) compiler infrastructure. It is safe, concise and fun to read and write. why kotlin ? kotlin is a statically typed programming that works in JVM, Android, JavaScript, and Native. It compiles to bytecode which makes a strong case for incorporating performance tuning into the development. some main features: 1. Open Source:  Kotlins is distributed under Apache License, Version 2.0. The kotlinc(Kotlin compiler), Intellij IDEA plugin, enhancements to basic Java libraries and build tools all are open source. 2. Interoperable with Java and Android:  It is designed with Java interoperability in mind. This means all current java and the android code works smoothly with kotlin. 3. Easy to Learn:  It is influenced by Java, Sc...