This chapter covers
- Functions for working with collections, strings, and regular expressions
- Using named arguments, default parameter values, and the infix call syntax
- Adapting Java libraries to Kotlin through extension functions and properties
- Structuring code with top-level and local functions and properties
By now, you should be fairly comfortable with using Kotlin the same way you use Java. You’ve seen how the concepts familiar to you from Java translate to Kotlin, and how Kotlin often makes them more concise and readable.
In this chapter, you’ll see how Kotlin improves on one of the key elements of every program: declaring and calling functions. We’ll also look into the possibilities for adapting Java libraries to the Kotlin style through the use of extension functions, allowing you to gain the full benefits of Kotlin in mixed-language projects.
To make our discussion more useful and less abstract, we’ll focus on Kotlin collections, strings, and regular expressions as our problem domain. As an introduction, let’s look at how to create collections in Kotlin.
Before you can do interesting things with collections, you need to learn how to create them. In section 2.3.4, you bumped into the way to create a new set: the setOf
function. You created a set of colors then, but for now, let’s keep it simple and work with numbers:
val set = setOf(1, 7, 53)
You create a list or a map in a similar way: