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.

...

...

...

  1. functions

    Code Block

...

  1. fun 

...

  1. theAnswer(

...

  1. ) 

...

...

...

https://kotlinlang.org/docs/reference/idioms.html#string-interpolation

...

  1. singleton

    Code Block

...

if ("john@example.com" in emailsList) { ... }

if ("jane@example.com" !in emailsList) { ... }
  1. object Resource {
        val name = "Name"
    }


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

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

...


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

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


  2. Use the fact that `return` and `throw` have type `Nothing`, https://kotlinlang.org/docs/reference/idioms.

...

...

...

...

...

  1. incomplete

    Code Block

...

  1. val x = foo(

...

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

    https://kotlinlang.org/docs/reference/idioms.

...

...

  1. fun transform(

...

https://kotlinlang.org/docs/reference/idioms.html#read-only-list

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

https://kotlinlang.org/docs/reference/idioms.html#accessing-a-map

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

https://kotlinlang.org/docs/reference/idioms.html#lazy-property

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

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

Code Block
fun String.spaceToCamelCase() { ... }

"Convert this to camelcase".spaceToCamelCase()

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

...

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


  2. Nullable truth.

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


  3. var x: String?; x = x ?: "Hello"; (analog for dart ?=)

    Code Block
    var x: String? = null
    x = x ?: "Hello"


  4. 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")


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

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


  6. https://kotlinlang.org/docs/reference/idioms.

...

...

https://kotlinlang.org/docs/reference/idioms.html#trycatch-expression

...

  1. String.spaceToCamelCase() { ... }
    
    "Convert this to camelcase".spaceToCamelCase()


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


  3. Using with/let/run to create a scope
  4. Using apply/also to add a finalizing action
    https://kotlinlang.org/docs/reference/idioms.

...

...

...

...

...

...

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


  2. Simple empty collection

    Code Block
    fun doSomething(additionalArguments: List<String> = emptyList())


  3. https://kotlinlang.org/docs/reference/idioms.

...

...

...

  1. map

    Code Block

...

  1. println(map["key"])
    map["key"] = 

...

  1. value


  2. Destructuring declaration (https://kotlinlang.org/docs/reference/idioms.

...

...

...

  1. pairs)

    Code Block

...

  1. for ((k, v) in map) {
        

...

  1. println("$k -> $v")
    }
    
    val (a,b) = Pair(1, 2)


  2. Public var with a private/protected setter

    Code Block
    var a: Int = 2
    	protected set // accessible only in descendents

    Mutable private - read-only public collections.

    Code Block
    ptivate val _list = ArrayList<Int>()
    val list: List<Int> get() = _list


  3. https://kotlinlang.org/docs/reference/idioms.

...

...

...

...

...

  1. collection

    Code Block

...

val stream = Files.newInputStream(Paths.get("/some/file.txt"))
stream.buffered().reader().use { reader ->
    println(reader.readText())
}
  1. if ("john@example.com" in emailsList) { ... }
    
    if ("jane@example.com" !in emailsList) { ... }


  2. ranges instead of for loops (https://kotlinlang.org/docs/reference/idioms.

...

  1. html#using-ranges):

    Code Block

...

  1. for (i 

...

  1. in 1..100) { ...

...

  1.  }  // closed 

...

  1. range: 

...

  1. includes 

...

  1. 100
    for 

...

  1. (

...

  1. i in 1 until 100) { ...

...

Non-local return

...

  1.  } // 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) { ... }


  2. Trailing lambdas (place lambda the last in the function parameters list, try to provide default values for parameters). Try to make such functions inline (to remove lambda creating overhead).

    Code Block
    fun integrate(from: Double = 0.0, to: Double = 1.0, function: (Double)→Double): Double {...}
    integrate{x→x*x + 2*x + 1}
    integrate(0.0, Pi){ sin(it) }
    


  3. .filter.map.reduce (collection processing, higher order functions) (https://kotlinlang.org/docs/reference/idioms.html#filtering-a-list)

    Code Block
    val list: List<Int> = listOf(1,2,3,4,5,6)
    
    val result = list
    	.filter{it%2 == 0} //select even numbers
        .map{it*it} // get square of each element
        .sumByDouble{it.toDouble()} //use one of reduce operations

...


  1. Assignment to `if`/`when`/`try`

    Code Block

...

class Doubles(val list: DoubleArray)

@Suppress("FunctionName")
fun Doubles(vararg numbers: Number) = Doubles(numbers.map{it.toDouble()}.toDoubleArray())

Doubles(1,2,3)

var x: String?; x = x ?: "Hello"; (analog for dart ?=)

Code Block
var x: String? = null
x = x ?: "Hello"

Public var with a private/protected setter

Code Block
var a: Int = 2
	protected set // accessible only in descendents

Mutable private - read-only public collections.

Code Block
ptivate val _list = ArrayList<Int>()
val list: List<Int> get() = _list

Trailing lambdas (place lambda the last in the function parameters list, try to provide default values for parameters). Try to make such functions inline (to remove lambda creating overhead).

Code Block
fun integrate(from: Double = 0.0, to: Double = 1.0, function: (Double)→Double): Double {...}
integrate{x→x*x + 2*x + 1}integrate(0.0, Pi){ sin(it) }
  1. val a = if(b>0) 0 else 1

    https://kotlinlang.org/docs/reference/idioms.html#trycatch-expression

    Code Block
    fun test() {
        val result = try {
            count()
        } catch (e: ArithmeticException) {
            throw IllegalStateException(e)
        }
    
        // Working with result
    }


    Code Block
    val ioResult: IOResult? = try{
      readFromFile() //assign result if it read is successful
    } catch(t: FileNotFoundException){
      null // return null if file not found
    }


  2. https://kotlinlang.org/docs/reference/idioms.html#builder-style-usage-of-methods-that-return-unit


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


  3. Scoped use of objects (https://kotlinlang.org/docs/reference/idioms.

...

...

...

...

...

  1. resources)

    Code Block
    val 

...

  1. stream = 

...

Nullable truth.

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

Assignment to `if`/`when`/`try`

Code Block
val a = if(b>0) 0 else 1

...

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


  2. Companion object. Use companion object as an ID
  3. Factory method instead of constructors

    Code Block
    class Doubles(val list: DoubleArray)
    
    @Suppress("FunctionName")
    fun Doubles(vararg numbers: Number) = Doubles(numbers.map{it.toDouble()}.toDoubleArray())
    
    Doubles(1,2,3)


  4. Lazy properties https://kotlinlang.org/docs/reference/idioms.html#lazy-property

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


  5. https://kotlinlang.org/docs/reference/idioms.html#convenient-form-for-a-generic-function-that-requires-the-generic-type-information

    Code Block
    //  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)


    Non-local return

    Code Block
    fun foo() {
        listOf(1, 2, 3, 4, 5).forEach {
            if (it == 3) return // non-local return directly to the caller of foo()
            print(it)
        }
        println("this point is unreachable")
    }


  6. DoubleArray vs Array<Double> vs List<Double>

Unsorted

  • Read line
Code Block
val map: MutableMap<String, Int>
val (a, b) = readlLine()?.split(" ") ?: error("No line to read") // read line and split it by given delimeter and use destructuring declaration
map[a] = b.toInt() // Convert the value on-flight and assign it

Simple empty collection

  • Use JMH for benchmarking