Look over the most important updates from the Kotlin Style Guide for Android with this handy introduction to naming, special characters, and more.
The official Kotlin Style Guide for Android has been maintained by Google on 2nd September 2017. The Android Kotlin Style Guides provides the full definition of coding standards for source code in Kotlin programming. A Kotlin source file is described as a part of the Google Android style. Like other programming style guides, Kotlin focuses on formatting issues as well as various types of convention and coding standards.
The Kotlin Style Guide for Android covers important updates, such as:
1. Naming
When the source file contains a single top-level element (e.g. class) then the file name should reflect the case-sensitive name with a .kt extension. For multiple top-level declarations, define the name that describes the source file and .kt extension.
class Chocos {}
// Chocobar.kt
class Chocobar {}
fun Runnable.toChocobar(): Chocobar = // …
// Map.kt
fun < T, O > Set < T > .map(func: (T) -> O): List < O > = // …
fun < T, O > List < T > .map(func: (T) -> O): List < O > = // …
2. Special Characters
Kotlin supports special characters, numbers, and Booleans that can be represented as primitive values during runtime. We can easily call properties and member functions on any variables.
Whitespace Characters
The ASCII horizontal space character (0x20) is the whitespace characters that appear in a source file. It means other whitespace characters in literals and strings are escaped. The tab characters are not used for indentation. The special escape sequence for any character has the sequence b, n, r, t, ‘, “, , and $ rather than the corresponding Unicode u221e.
Non-ASCII Characters
The Unicode characters (e.g. ∞) or the Unicode escape (e.g. u221e) are used for the Non-ASCII characters. The perfect use of both characters depends upon the code, which is easier to read and understand. Unicode escapes discourage the printable characters as well as string literals and comments.
ExampleDiscussion
val unitAbbrev = “μs”
Good : clear without a comment.
val unitAbbrev = “u03bcs” // μs
Poor : there’s no reason to use an escape with printable character
val unitAbbrev = “u03bcs”
Poor : the reader has no idea what this is about.
return “ufeff” + content
Good: use escapes for non-printable characters & comment if necessary
3. Formatting
Kotlin offers support for the use of UTF-8 character encoding in the source file. Soft tabs are used, tab characters which are converted to spaces. Every major element in the Kotlin language is defined and separated from the single blank line. Single line lambdas /class/objects/enums use curly braces on the same lines, such as:
class Person(val firstName: String, val lastName: String, val age: Int){}
Braces
if (string.isEmpty()) return
when(value) {
0 ->
return
}
Braces are required for if, for, do, while, and when statements, when the body contains a single statement, or empty, such as:
if (string.isEmpty())
return // not right
if (string.isEmpty()) {
return // right
}
Non-Empty Blocks
Kernighan & Ritchie style (Egyptian brackets) is followed by braces to construct block and non-empty blocks.
- After the opening brace, line break.
- Before the closing brace, line break.
- No line break before the opening brace.
- Line break after the closing brace only if the brace terminates a statement, function body, constructor, or class.
return Runnable {
while (condition()) {
foo()
}
}
return object: MyClass() {
override fun foo() {
if (condition()) {
try {
something()
} catch (e: ProblemException) {
recover()
}
} else if (otherCondition()) {
somethingElse()
} else {
lastThing()
}
}
}
Empty Blocks
An empty block or construct block must be defined in Kernighan & Ritchie style (Egyptian brackets):
try {
doSomething()
} catch (e: Exception) {} // WRONG!
try {
doSomething()
} catch (e: Exception) {} // Okay
4. Line Wrapping
Any line of code that exceeds the column limit of 100 characters must be line wrapped as explained below:
Exceptions:
- A line obeying the column limit is not possible, such as long URLs.
- In the comment, column lines may be pasted and cut into the shell.
- Import and package statements.
Functions
A function signature defines each parameter declaration in its own line. Function parameter uses the continuation indent (+7), closing parenthesis & return type.
fun < T > Iterable < T > .joinToString(
separator: CharSequence = ", ",
prefix: CharSequence = "",
postfix: CharSequence = ""
) String {}
Expression Functions
A function that contains a single expression is represented as an expression function. When expression functions grow, they require wrapping, so use a normal function body, a return type declaration, and normal expression wrapping rules.
override fun toString(): String {
return "Hey"
}
override fun toString(): String = "Hey"
5. Indentation
We can easily apply the indent level to both comments and code in the block. Whenever a new block and construct block is opened, the indent increases by four spaces. When the block ends, the indent returns to the old indent level.
6. Lambdas
Lambdas are one of the best tools in Kotlin programming. They allow modular function in a simpler way. Below, you’ll find the style guideline for Lambdas:
- “it” keyword is used to access the single argument and single line lambdas parameter.
- Lambdas’ limit for nesting is up to 4 levels.
- When lambdas code is used for multiple times or contains more lines, it is preferred to defining and using the function.
- Define a single lambda parameter for single argument in lambda like this:
kotlin
list.filter {
it > 10
}.map {
element ->
processElement(element)
element * 2
}
The Kotlin style guide primarily focuses on conciseness, simplicity, and readability. Google has announced Kotlin programming language support for Android app development. This increases the excitement among programming enthusiasts. Kotlin 1.2 RC (released candidate) comes with new improvements and experimental support for Android application development.
Source: https://dzone.com/articles/introduction-to-android-kotlin-style-guides