The Kotlin Journey Part IV: Adding functionality

This is a multi-part series on Kotlin, a new statically typed language from JetBrains targeting the JVM and JavaScript

Part I: Getting things set up
Part II: A primer on classes
Part III: Wrapping up classes
Part IV: Adding functionality

All the goodies you’d expect

Up to now we’ve seen how to work with classes and only slightly touched on the subject of functions in Kotlin, reason being that functions deserve their own section, as they play a very important role in Kotlin and expose a lot of the potential the language offers. Let’s dive in a bit more now.

Functions in Kotlin are declared using the keyword fun. By default, if we do not specify a return type, Unit is returned which would be the equivalent of void, although we do not need to explicitly indicate it. Parameters, much like constructors of classes that we’ve already seen, follow the Pascal convention of name colon type.

If you’re coming from a C# background, expect pretty much everything you have in C#, including:

Optional parameters

image

The last parameter being passed in to the logMessage function is optional (like C# they always need to be at the end). If nothing is supplied, a default value is used. In this case, it’s using the current date time by instantiating an instance of Date.

Named parameters

We can also call functions using names to reference parameters, making the order of which we pass arguments in irrelevant

image

Variable number of parameters

If we want to pass in a random number of arguments, we can prefix a parameter with the keyword vararg which by default creates an array of the type of the parameter

image

As such the example above would be an array of Integers.

Statics in Kotlin

The concept of static methods doesn’t really exist in Kotlin as functions can be declared as top-level. As such, we can define a series of functions in a module and then have access to all of them by merely referencing the module. Therefore there’s no real need for statics. We can also declare one function local to another, much like in Pascal.

Reducing amount of code with single-line functions

If a function consists of single line of code, whether or not it returns a value, we can omit curly braces and reduce a little bit the number of characters. For instance, the previous logMessage could be written out as:

image

The compiler can infer the return type, so even if we were to return a value, we wouldn’t need to explicitly declare it.

enabling fluent code

Kotlin allows us to reduce some of the noise that is usually associated with certain programming languages, by offering a series of features that enable us to write code that is somewhat a bit more fluent, or closer to natural languages.

To begin with, any function that takes two parameters can be called in infix notation. This means that we can do things such as:

image

where plus and equals are functions that take two arguments (and defined as single-line for brevity):

image

Kotlin also allows extensions functions, thus allowing us to extend a class with functionality without having to inherit from it. If you’re a C# programmer, you’re familiar with extension methods. Only difference is that in Kotlin, the declaration is more succinct:

image

This adds a new function to the String class called console (takes no parameters). Inside the function, we can refer to the object itself using the keyword this. Notice how as opposed to C#, we do not have to create a static class, a static function, or pass this as the first parameter.

And of course, extension functions can also be called using infix notation. By defining the extension then to be:

image

we can write code like this:

image

not that I’m saying we should write the code above, but you get the point. It opens up many possibilities.

Adding function literals and high-order functions to the mix

Functions in Kotlin can take other functions as parameters. Combined with function literals (or lambda expressions), it allows us to write the following:

image

Here we have a function callFunctions that takes as parameter a function that takes itself two parameters (of type Int) and returns an Int. We then call this function in two different ways: passing in as parameter a function previously declared (sumNumbers) or passing in a function literal.

Last but not least, we can even define extension functions using function literals:

image

Combining all of these things, we can then start building nice, fluent and statically typed DSL’s

Summary

We’ve seen a brief overview of some of the functionality Kotlin provides with functions (pun not intended). There are quite a few other important features such as the ability to override operators using conventions (i.e. to override +=, define a function called plusAssign), as well as some the ability to drop braces when functions only have one arguments, inline functions, local functions etc. For more information about these and other features, check out the function section on the documentation page.

5 thoughts on “The Kotlin Journey Part IV: Adding functionality

  1. Pingback: The Kotlin Journey Part III: Wrapping up classes « Hadi Hariri's Blog

  2. Pingback: The Kotlin Journey Part I : Getting things set up « Hadi Hariri's Blog

  3. Pingback: The Kotlin Journey Part II: A primer on classes « Hadi Hariri's Blog

  4. marioosheck

    Nice articles, thank you. I wanted to learn Scala but after reading some docs and books I’ve thought Is’nt good idea. When I saw Kotlin first time that made me sure this is language I’m waiting for. Kotlin better fits my needs, easy to learn and fast has fast compilation time:)

    Good work!

    Reply
  5. Pingback: Extension Function Literals in Kotlin or “How to enforce restrictions on your DSL” « Hadi Hariri's Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s