Clean code in Kotlin
Kotlin’s coding conventions: classes in upper camel case, functions and variables in camel case that starts lowercase, constants in screaming snake case, 4 spaces a level, and val rather than var whenever a value never changes.
What does Kotlin’s coding conventions ask for?
Names of packages are always lowercase and do not use underscores (org.example.project).
source
How should Kotlin code look?
- Four spaces, no tabs. source
How are names written in Kotlin?
| Kind | Example | Rule |
|---|---|---|
| Types | ShoppingCart | Classes in upper camel case. source |
| Functions | addItem | Functions, properties and locals in camel case, lowercase first. source |
| Variables | itemCount | Functions, properties and locals in camel case, lowercase first. source |
| Constants | MAX_ITEMS | Constants in screaming snake case. source |
What does cleaner Kotlin look like?
class DiscountManager {
fun Calc_discount(total: Double): Double {
var d = 0.0
if (total > 1000) d = total * 0.05
return d
}
}const val DISCOUNT_THRESHOLD = 1000.0
const val DISCOUNT_RATE = 0.05
class DiscountRule {
fun calculateDiscount(total: Double): Double =
if (total > DISCOUNT_THRESHOLD) total * DISCOUNT_RATE else 0.0
}Other languages
More on clean code: comments, functions, naming and the checklist.