This document defines the conventions for writing Kotlin code at Cookpad.
We follow Kotlin official Coding Conventions , the styles of naming, spaces, line-breaks, and the others unless there is a special mention.
This guide aims to accomplish the following objectives:
- Clarify purpose
- Improve readability
- Keep consistency
- Reduce side-effects
- [SHOULD] Put
,
at the end of elements in Enum.- Reduce the difference when we add new elements.
// Bad
enum class Color {
RED,
BLUE,
GREEN
}
// Good
enum class Color {
RED,
BLUE,
GREEN,
}
- [MUST] Put lambda expression out of
()
when last argument type of method is function.
// Bad
val ints = Array(5, { it * 2 })
// Good
val ints = Array(5) { it * 2 }
- [MUST] Omit
()
when method has only one argument that is function.
// Bad
val nums = ints.map({ it * it })
// Good
val nums = ints.map { it * it }
- [MUST] Do not use
Unit
as return type.
// Bad
fun method(): Unit {
// do something
}
// Good
fun method() {
// do something
}
- [MUST] Use
!!
only when you would like to explicit Non-Null variables - [SHOULD] Use
?:
operator as possible to check null value in assignment expression.
// Bad
val message = if (e != null) e.message else ""
// Good
val message = e.message ?: ""
- [MUST] Assign a label for a lambda in nested lambda expressions.
- [MUST] Declare parameter names in nested lambda expressions.
- [SHOULD] Declare parameter names in single lambda expressions.
// BAD
fun run() {
hogeEntity?.let { hoge ->
hoge.fugaEntity?.let { fuga ->
if (!fuga.isEmpty()) {
return@let
}
}
}
}
// GOOD
fun run() {
hogeEntity?.let parent@ { hoge ->
hoge.fugaEntity?.let child@ { fuga ->
if (!fuga.isEmpty()) {
return@child
}
}
}
}