Kotlin Tip #6: Explore Range Expressions with ‘..’— 100 Kotlin Tips in 100 Days
Twitter | LinkedIn | YouTube | Instagram
Tip #5: Adopt the Safe Call & the Elvis Operators
In Kotlin, one of the handiest features you’ll come across is range expressions. They’re a simple yet powerful way to define a sequence of values for looping through numbers in a for loop or checking if a value falls within a certain boundary.
Basic Iteration
A Range Expression is like a shortcut for listing all the numbers from one point to another. Traditionally, you need a for-loop to achieve it, as in the example below where we're iterating between one and five (inclusive):
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
In contrast, Kotlin introduces a more straightforward and elegant syntax for defining ranges. Let's take a look at how it would look like when doing the iteration in Kotlin:
This loop prints numbers 1 through 5 using Kotlin’s range expression 1..5, which is concise and readable. For exclusive ranges, until
can be used, enhancing clarity:
Value Checks within Ranges
Checking if a value falls within a range is straightforward in Kotlin. Traditionally, this check might be verbose:
In Kotlin, this check is concise:
Reverse Ranges and Skipping Numbers
Kotlin supports reverse ranges and stepping through ranges seamlessly:
Characters and Custom Objects
Kotlin extends range expressions to include characters:
For custom objects, Kotlin allows the creation of range expressions by defining a rangeTo
operator function. This enables using the ..
syntax with instances of custom classes:
Range Expressions cut down on code clutter and help prevent common mistakes, making it easier to write and maintain clean code. It’s a clear example of Kotlin’s ability to improve the coding process, showcasing why embracing such streamlined tools is crucial for clear, safe, and concise programming.
I hope you have enjoyed the sixth tip of our series! Don’t forget to subscribe and stay tuned for more Kotlin tips!
Stay curious!
Tip #7: Make Use Of Extension Functions
Contribute
Writing takes time and effort. I love writing and sharing knowledge, but I also have bills to pay. If you like my work, please, consider donating through Buy Me a Coffee: https://www.buymeacoffee.com/RaphaelDeLio
Or by sending me BitCoin: 1HjG7pmghg3Z8RATH4aiUWr156BGafJ6Zw
Follow Me on Social Media
Stay connected and dive deeper into the world of Kotlin with me! Follow my journey across all major social platforms for exclusive content, tips, and discussions.