Shorthand Notation for Simple Functions
Explore how to refactor Kotlin functions into a more concise shorthand notation. Understand when to use this syntax and how Kotlin's type inference can simplify your code while maintaining readability.
We'll cover the following...
Functions that simply return the result of a single expression can be abbreviated in Kotlin.
Refactoring a Function #
Consider the following function:
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:
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 expression.
But in Kotlin, you can go one ...