kotlin idoms introduction

Kotlin Programming language idioms Tutorial with code examples

In this article, we will discuss and learn about most frequently used Kotlin idioms in Kotlin programming language.

Creating Data Classes in Kotlin (DTO / POJO) example.

Data classes are model classes which we often create to hold data. In Java, we create POJO classes and then we need to define getter and setter functions for each member variable of a class, which is lot of boiler plate code.

But in Kotlin its very easy to define a POJO class we just have to write three words. keyword ‘data’, class ,  class name, and its member variables.

data class User(val name: String, val age: Int)

And the compiler automatically generates utility methods for User class.

In addition to getter and setter compiler also generates componentN() and copy() method.

Default function arguments

Functions in Kotlin example

Functions in Kotlin are declared using ‘fun’ keyword.

fun double(x: Int) : Int {
return 2 * x
}

fun (keyword used to define function)

double (function name)

x (function argument)

Int (argument type)

: Int  (function return type, Int in this case)

Default functions

In Java, if you want to pass different number of arguments to a function you need method overloading. But in Kotlin you can call same method with different number of arguments.

In Kotlin we can pass default values to function arguments in function declaration.

Let me give you an example how default arguments work in Kotlin programming language.

fun main(args: ArrayList<String>) {
      foo() // calling function without any arguments. 
 }
// As no value is passed to function even than this will be called 
// and default values will be assigned to function arguments.
fun foo(ch: Char = 'a', num: Int = 0) {
}

As you can see in code above You can call function foo() from main without passing any argument even when function foo(a,0) requires two arguments to be passed.

If no argument is passed to function,it will use default values defined in argument (already explained)

So ‘a’ will be assigned to variable ch and ‘0’ will be assigned to variable num.

How to filter a list in Kotlin example

There are several ways for filtering collections in Kotlin language.

For example you have list of months

  val months = listOf("January", "February", "March") 

And you want to filter values matching “January”.

months.filter { month -> month == "January" }

If you want list which do not contain “January” you will use filterNot.

months.filterNot { it == "January" }

The filter standard library accepts lamda expression as an argument we call such methods in Kotlin Higher order functions.

String interpolation and String Templates in Kotlin example

String templates allow string to contain template expressions.

Which means template expression can be interpolated (evaluated) and its value can be concatenated in String.

we do not need to explicitly concatenate string in Kotlin instead String interpolation does the job for us.

$ sign is used for String interpolation in Kotlin language.

Template expression start with $ dollar sign.

// String template expression example
val i = 10 val s = "i = $i" // evaluates to "i = 10"

or an arbitrary expression in curly braces:

val s = "abc"
val str = "$s.length is ${s.length}" // evaluates to "abc.length is 3"

In above line of code we have applied string interpolation not only on val ‘s’ instead we have applied interpolation on ‘s.length’.  Because variable length also depends on ‘s’ so it has to be interpolated with ‘s’ using curly braces, we cannot apply $ symbol on length variable.

Instance checks or Type checking in Kotlin example

We can check if an object confirms to a given object type during runtime.

For example

when (x) {
 is Foo -> ...  (true if x is of type Foo) 
 is Bar -> ...  (true if x is of type Bar)
 else -> ...    (true if none of the above condition is met) 
}

when  is equivalent to switch statement in Java / C. when matches its value against all branches until condition is satisfied.

Above code will check if x is of type Foo or Bar. If none of the condition is true execution will be passed to else statement.

Another instance check example

if (obj is String) {
 print(obj.length)     // if obj is of type String print its length 
}

negate of above code using ! operator.

if (obj !is String) {
 print("obj is not a String") 
}

Traversing a map / list of pairs in Kotlin example

In this section we will learn how to traverse key value objects in Kotlin programming language.

Traversing map in Kotlin using for loop example.

Using Ranges in Kotlin

For example

// using double dot operator in Kotlin,
// range variable will contain value from 1,2,3,4,5

    val range = 1.. 5

if you want to store range of values in decending order use downTo operator.

// using double dot operator in Kotlin,
// range2 variable will contain value in this sequence 5,4,3,2,1

    val range2 = 5 downTo 1

Another Range in Kotlin example if you want to skip a number in Kotlin Range:

// using step operator, it will skip every second value.
// range variable will contain values 1,3,5

    val range3 = 1..5 step 2

In Kotlin you can also define range for characters.

// range4 variable will contain values from a,b,c,d..... z

 val range4 = 'a'..'z'

Range expressions are formed with RangeTo() functions.

Now if you want to iterate through a range in kotlin.

for loop can iterate through anything that provides ranges.

Below are different ways to iterate through a range in Kotlin.

for (i in 1..4)
 print(i)      //  print 1234

If want to iterate over a number in reverse order.

You can use downTo() utility method.

for (i in 4 downTo 1) 
  print(i)    // prints "4321"

Read-only list kotlin example

You can create immutable lists in Kotlin using several different methods.

For example

listOf()

listof method returns an instance of ArrayList and it is immutable.

Example:

val list = listOf("a", "b", "c")

Returns a new list of read only elements. The returned list is serializable.

It only allows read-only operations like size, get means it can only be traversed.

If you wants to add, remove from collection in Kotlin you can use mutablelistof method from Collections.

Recommended Reading :-

Classes, Objects, Modifiers and Interfaces in Kotlin Tutorial

How to Develop Android Image Gallery App using Kotlin – Tutorial with Complete Source Code

If you want to know more about Kotlin upcoming features.

Thank you for reading. If it helped share this article and comment below for any suggestion or improvement.

Posts created 26

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top