Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
  1. https://kotlinlang.org/docs/reference/idioms.html#string-interpolation

    Code Block
    println("Name $name")


  2. Prefer read-only `val` over mutable `var`

    Code Block
    /* bad */
    var counter = 0
    for(i in 0..20){
      counter += i
    }
    
    /* preferred */
    val sum = (0..20).sum()


  3. Unit as a return type

    Code Block
    fun doSomething(): Unit{
      println("do something")
    }


  4. https://kotlinlang.org/docs/reference/idioms.html#single-expression-functions

    Code Block
    fun theAnswer() = 42


  5. https://kotlinlang.org/docs/reference/idioms.html#default-values-for-function-parameters

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


  6. https://kotlinlang.org/docs/reference/idioms.html#creating-a-singleton

    Code Block
    object Resource {
        val name = "Name"
    }


  7. https://kotlinlang.org/docs/reference/idioms.html#instance-checks

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


  8. https://kotlinlang.org/docs/reference/idioms.html#creating-dtos-pojospocos

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


  9. Use the fact that `return` and `throw` have type `Nothing`, https://kotlinlang.org/docs/reference/idioms.html#todo-marking-code-as-incomplete

    Code Block
    val x = foo() ?: return notFound()
    
    val y = if(conditionSatisfied()){
      1.0
    } else {
      error("Condition is not satisfied"}//throws inside, the type is Nothing
    }


  10. Nullable truth.

    Code Block
    a?.b == true 
    //instead of 
    a?.b ?: false


  11. Safe chain and elvis (https://kotlinlang.org/docs/reference/idioms.html#if-not-null-and-else-shorthand)

    Code Block
    val files = File("Test").listFiles()
    
    println(files?.size ?: "empty")


  12. https://kotlinlang.org/docs/reference/idioms.html#execute-if-not-null

    Code Block
    val value = ...
    
    value?.let {
        ... // execute this block if not null
    }


  13. https://kotlinlang.org/docs/reference/idioms.html#extension-functions

    Code Block
    fun String.spaceToCamelCase() { ... }
    
    "Convert this to camelcase".spaceToCamelCase()


  14. Extension properties

    Code Block
    import java.util.Calendar
    
    var Calendar.year
        get() = get(Calendar.YEAR)
        set(value) = set(Calendar.YEAR, value)
    
    val calendar = Calendar.getInstance()
    println(calendar.year) // 2020
    calendar.year = 2021
    println(calendar.year) // 2021


  15.  With block
  • Companion object

https://kotlinlang.org/docs/reference/idioms.html#checking-element-presence-in-a-collection

...