...

/

Shorthand Notation for Simple Functions

Shorthand Notation for Simple Functions

Learn when and how to write functions in shorthand notation for concise and readable code.

Functions that simply return the result of a single expression can be abbreviated in Kotlin.

Refactoring a Function #

Consider the following function:

Press + to interact
fun isValidUsername(username: String): Boolean {
if (username.length >= 3) {
return true
} else {
return false
}
}

How would you refactor it? Can you make it more concise and improve its readabilty?

You could improve this in several steps, e.g., by moving out the return keyword and using if as an expression. This particular example is even simpler and can be rewritten as:

Press + to interact
fun isValidUsername(username: String): Boolean {
return username.length >= 3
}

This is the simplest form this function could take in many other languages such as Java or C++. The function body of isValidUsername consists only of a return keyword followed by an ...