Top 20 Daily used Kotlin Code Snippet

0
441
Daily used Kotlin Code Snippet
Daily used Kotlin Code Snippet

In past month i did some work on Kotlin and some article you can see on this trending topic. So today i am here with the list of daily used Kotlin code snippet which every developer need to know.

It is a collection of random and frequently used idioms in Kotlin. If you have a favorite idiom, contribute it by sending a comment below.

List of Daily used Kotlin Code Snippet

1Creating DTOs (POJOs/POCOs)

data class Customer(val name: String, val email: String)

provides a Customer class with the following functionality:

  • getters (and setters in case of var{: .keyword }s) for all properties
  • equals()
  • hashCode()
  • toString()
  • copy()
  • component1()component2(), …, for all properties (see Data classes)

Do you know : What is Kotlin Native?

2Default values for function parameters

fun foo(a: Int = 0, b: String = "") { ... }

3Filtering a list

val positives = list.filter { x -> x > 0 }

Or alternatively, even shorter:

val positives = list.filter { it > 0 }

Do you use this : Koin – Kotlin Dependency Injection

4String Interpolation

println("Name $name")

5Instance Checks

when (x) {
    is Foo -> ...
    is Bar -> ...
    else   -> ...
}

6Traversing a map/list of pairs

for ((k, v) in map) {
    println("$k -> $v")
}

kv can be called anything.

7Using ranges

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..10 step 2) { ... }
for (x in 10 downTo 1) { ... }
if (x in 1..10) { ... }

Recommended article : Top 30 Android Tools Every Developer should Know

8Read-only list

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

9Read-only map

val map = mapOf("a" to 1, "b" to 2, "c" to 3)

10Accessing a map

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

11Lazy property

val p: String by lazy {
    // compute the string
}

Did you know : Disadvantage of Kotlin – You must know before use

12Extension Functions

fun String.spaceToCamelCase() { ... }

"Convert this to camelcase".spaceToCamelCase()

13Creating a singleton

object Resource {
    val name = "Name"
}

14If not null shorthand

val files = File("Test").listFiles()

println(files?.size)

15If not null and else shorthand

val files = File("Test").listFiles()

println(files?.size ?: "empty")

Read this too : 5 cool things you probably don’t know about Kotlin

16Executing a statement if null

val data = ...
val email = data["email"] ?: throw IllegalStateException("Email is missing!")

17Execute if not null

val data = ...

data?.let {
    ... // execute this block if not null
}

18Map nullable value if not null

val data = ...

val mapped = data?.let { transformData(it) } ?: defaultValueIfDataIsNull

19Return on when statement

fun transform(color: String): Int {
    return when (color) {
        "Red" -> 0
        "Green" -> 1
        "Blue" -> 2
        else -> throw IllegalArgumentException("Invalid color param value")
    }
}

20‘try/catch’ expression

fun test() {
    val result = try {
        count()
    } catch (e: ArithmeticException) {
        throw IllegalStateException(e)
    }

    // Working with result
}

21‘if’ expression

fun foo(param: Int) {
    val result = if (param == 1) {
        "one"
    } else if (param == 2) {
        "two"
    } else {
        "three"
    }
}

22Builder-style usage of methods that return Unit

fun arrayOfMinusOnes(size: Int): IntArray {
    return IntArray(size).apply { fill(-1) }
}

23Single-expression functions

fun theAnswer() = 42

This is equivalent to

fun theAnswer(): Int {
    return 42
}

This can be effectively combined with other Kotlin code snippet, leading to shorter code. E.g. with the when{: .keyword }-expression:

fun transform(color: String): Int = when (color) {
    "Red" -> 0
    "Green" -> 1
    "Blue" -> 2
    else -> throw IllegalArgumentException("Invalid color param value")
}

Scratch tutorialCreate Reddit like Android Kotlin app Step by Step

24Calling 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()
}

25Java 7’s try with resources

val stream = Files.newInputStream(Paths.get("/some/file.txt"))
stream.buffered().reader().use { reader ->
    println(reader.readText())
}

26Convenient form for a generic function that requires the generic type information

/  public final class Gson {
//     ...
//     public <T> T fromJson(JsonElement json, Class<T> classOfT) throws JsonSyntaxException {
//     ...

inline fun <reified T: Any> Gson.fromJson(json: JsonElement): T = this.fromJson(json, T::class.java)

27Consuming a nullable Boolean

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

 

I hope you like this article and it would be helpful.

Share your thoughts

Loading Facebook Comments ...
Loading Disqus Comments ...