Constants in Kotlin — what’s a recommended way to create them?

Avoid using companion objects. Behind the hood, getter and setter instance methods are created for the fields to be accessible. Calling instance methods is technically more expensive than calling static methods. public class DbConstants { companion object { val TABLE_USER_ATTRIBUTE_EMPID = “_id” val TABLE_USER_ATTRIBUTE_DATA = “data” } Instead define the constants in object. Recommended practice … Read more

How do I initialize Kotlin’s MutableList to empty MutableList?

You can simply write: val mutableList = mutableListOf<Kolory>() This is the most idiomatic way. Alternative ways are val mutableList : MutableList<Kolory> = arrayListOf() or val mutableList : MutableList<Kolory> = ArrayList() This is exploiting the fact that java types like ArrayList are implicitly implementing the type MutableList via a compiler trick.

Smart cast to ‘Type’ is impossible, because ‘variable’ is a mutable property that could have been changed by this time

Between execution of left != null and queue.add(left) another thread could have changed the value of left to null. To work around this you have several options. Here are some: Use a local variable with smart cast: val node = left if (node != null) { queue.add(node) } Use a safe call such as one … Read more

How to check if a “lateinit” variable has been initialized?

There is a lateinit improvement in Kotlin 1.2 that allows to check the initialization state of lateinit variable directly: lateinit var file: File if (this::file.isInitialized) { … } See the annoucement on JetBrains blog or the KEEP proposal. UPDATE: Kotlin 1.2 has been released. You can find lateinit enhancements here: Checking whether a lateinit var … Read more