Skip to main content

Kotlin Idioms

Idioms

Random and frequently used in kotlin.

Creating Data classes in kotlin (POJOs/DTOs)

Data classes are model classes which are created to hold data. In Java, we usually create POJO classes with getter and setter methods for each member variable of a class. But in Kotlin, POJO class can be created within a single line of code with keywords: 'data', 'class', 'class name' and its member variables.

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

provides a Student class with the following functionality:
- getters(and setters in case of vars) for all properties
- equals()
- hashCode()
- toString()
- copy()
- object1(), object2(), ..., for all properties.

Filter a list in kotlin

There are several ways to filter a list in kotlin.
For example:
val fruits = listOf("Apple", "Banana", "Orange")                                                              
And we will filter values matching "Apple".
fruits.filter { fruit  ->  fruit == "Apple" }                                                                        
And If we do not want Apple in our list we will use filterNot.
fruits.filterNot { it == "Apple" }                                                                                      
Lambda expressions are accepted by filter standard library and such methods are called Higher-order functions in Kotlin.

Expressions in kotlin

Use 'when' as expression body:
fun parseNum(number: String): Int?{
       when (number) { 
                 "one" -> return 1
                 "two" -> return 2
                 else -> return null
       }

Alternative way:
fun parseNum(number: String) =
       when (number) {
                "one" -> 1
                "two" -> 2
                 else -> null
       }                                                                                                        

Use 'try' as expression body:
fun tryParse(number: String): Int? {
      try{
             return Integer.parseInt(number)
     }
     catch (e: NumberFormatException) {
            return null
     }
}

Alternative way:
fun tryParse(number: String) =
      try{
           return Integer.parseInt(number)
       }
       catch (e: NumberFormatException) {
         return null
      }                                                                                                                                                

Ranges in kotlin

Using double dot operator, a range can be defined in kotlin as examples below: 
for  (i in 1.. 100) { ... }       // closed range: includes 100
for (i in 1 until 100) { ... }  // half-open range: does not include 100
for (x in 2.. 20 step 2) { ... }
for (x in 10 downTo 1) { ... }
if (x in 1..10) { ... }

Use range checks instead of comparison pairs:
fun isLatinUppercase(c: Char) =
       c >= 'A'  && c <= 'Z'

Alternative way:
fun isLatinUppercase(c: Char) =
       c in 'A.. 'Z'

Accessing a map in kotlin

println(map["key"])
map["key"] = value

Calling multiple methods on an object instance('with')

class Turtle { fun penDown() fun penUp() fun turn(degrees: Double) fun forward(pixels: Double) } val myTurtle = Turtle() with(myTurtle) { //draw a 100 pix square penDown() for(i in 1..4) { forward(100.0) turn(90.0) } penUp() }

Consuming a nullable Boolean

val b: Boolean? = ...
if (b == true) { ... } else { // `b` is false or null }

Know more about kotlin Idioms
Thank you for reading and share this article if it is helpful for you.

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 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 modifi...