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

Getting Started With Laravel & React.

Getting started with Laravel & React  is easy now with Laravel version 5.5 which is the next long term support (LTS) version of Laravel (the last being 5.1).  In prior versions of Laravel, only Vue scaffolding is included, but with the release of Laravel 5.5, new front-end preset options are available for bootstrap and React including Vue. In a fresh installation of Laravel 5.5, you can easily swap your Vue scaffolding to React scaffolding using the " php artisan preset react " command. The default Mix configuration, components, and all other related files will be updated accordingly. Now to understand it more let's get started with simple Laravel 5.5 & React demo project. First, choose a directory or folder where you want to place your Laravel project then open a terminal and copy the below command: composer create-project --prefer-dist laravel/laravel="5.5.*" DemoProject After successful completion, we need to change our Vue