Let’s see how we can apply Joshua Bloch’s Effective Java in the Kotlin world. Today’s topic is General Programming.
Item 57: Minimize the scope of local variables
In Kotlin, we can use standard functions such as let()
for minimize the scope, e.g.:
getAReference().let { ref ->
...
}
// the reference is no longer visible here
Item 58: Prefer for-each loops to traditional for loops
In Kotlin, we can also use forEach() or other extension functions to loop over a collection.
Item 59: Know and use the libraries
There is nothing special in Kotlin for this item.
Item 60: A void float and double if exact answers are required
There is nothing special in Kotlin for this item.
Item 61: Prefer primitive types to boxed primitives
Note that in Kotlin, non nullable types like Int
are translated into primitive types like int
, while nullable types like Int?
are translated to boxed primitives like Integer
.
Item 62: Avoid strings where other types are more appropriate
There is nothing special in Kotlin for this item.
Item 63: Beware the performance of string concatenation
There is nothing special in Kotlin for this item.
Item 64: Refer to objects by their interfaces
There is nothing special in Kotlin for this item.
Item 65: Prefer interfaces to reflection
There is nothing special in Kotlin for this item.
Item 66: Use native methods judiciously
There is nothing special in Kotlin for this item.
Item 67: Optimize judiciously
There is nothing special in Kotlin for this item.
Item 68: Adhere to generally accepted naming conventions
Coding style for Kotlin can be found here.