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) { ... }
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'
c >= 'A' && c <= 'Z'
Alternative way:
fun isLatinUppercase(c: Char) =
c in 'A' .. 'Z'
c in 'A' .. 'Z'
Accessing a map in kotlin
println(map["key"])
map["key"] = value
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 }
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
Post a Comment