Chapter 3. functions: Getting Out of Main

image

It’s time to take it up a notch, and learn about functions.

So far, all the code you’ve written has been inside your application’s main function. But if you want to write code that’s better organized and easier to maintain, you need to know how to split your code into separate functions. In this chapter, you’ll learn how to write functions and interact with your application by building a game. You’ll discover how to write compact single expression functions. Along the way you’ll find out how to iterate through ranges and collections using the powerful for loop.

Let’s build a game: Rock, Paper, Scissors

In all the code examples you’ve seen so far, we’ve added code to the application’s main function. As you already know, this function launches your application as it’s the function that gets executed when you run it.

This approach has worked well while we’ve been learning Kotlin’s basic syntax, but most applications in the real-world split the code across multiple functions. This is because:

image

Each function is a named section of code that performs a specific task. As an example, you could write a function named max that determines the highest value out of two values, and then call this function at various stages in your application.

Get Head First Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.