Regular Expressions
In general, it is a good idea to check inputs before performing “dangerous” operations that could cause your program to crash. There are several approaches you can take to prevent your application from crashing when it receives invalid input. There are also ways to handle errors after they happen, which you will see in Chapter 7.
For now, you will prevent this crash by making sure the user has entered a number before attempting to call toInt on it. Specifically, you will ensure that the string returned by readLine only contains digits. Kotlin has many tools in place that can help you check that a user’s input is valid. One technique makes use of a regular expression – a commonly used tool for parsing and working ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access