3 Defining and calling functions

 

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 on a basic level, the same way you might have used other object-oriented languages, like Java, before. 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.

3.1 Creating collections in Kotlin

 

3.2 Making functions easier to call

 
 
 

3.2.1 Named arguments

 
 

3.2.2 Default parameter values

 
 

3.2.3 Getting rid of static utility classes: Top-level functions and properties

 
 
 

3.3 Adding methods to other people’s classes: Extension functions and properties

 
 
 

3.3.1 Imports and extension functions

 
 
 
 

3.3.2 Calling extension functions from Java

 
 
 

3.3.3 Utility functions as extensions

 
 

3.3.4 No overriding for extension functions

 
 
 

3.3.5 Extension properties

 

3.4 Working with collections: varargs, infix calls, and library support

 
 

3.4.1 Extending the Java collections API

 
 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest