Kotlin is a statically typed language that runs on JVM that may compile to JavaScript source code or use the LLVM compiler infrastructure. Since then, it’s grown exponentially in popularity. In 2017, Google officially backed Kotlin as the official language for Android.
And that's just the beginning! Join us here at Kotlin Town and be a part of the evolution of this exciting new language.
Welcome toKotlin Thursdays! This week I’m starting a series on functional programming with Kotlin. Functional programming is something I’m passionate about, and Kotlin has some great functional programming support! Functional programming can lead to code that is easier to think about, has fewer bugs and is easier to test.
What better way to dive into functional programming than to learn about functions! It might help to think of functions as “mini-programs”. Functions allow us to write some code once and then use that code multiple times throughout the rest of our program.
The Main Function
To make a Kotlin program, we need to make a function to “kickstart” our program. This function is called themainfunction. To create themainfunction, let’s make a file calledFunWithFunctions.ktand write the following code in it:
fun main() { println(“Hello World!”) }
We can compile this into a jar file that we can run with the following command on our terminal:
Then we can run the program with the following command:
java -jar functions.jar
For those not familiar, a jar file is how Java Virtual Machine programs are packaged into programs that we can easily run. Kotlin, like Java, uses the Java Virtual Machine to run.
Kotlin knows that when we run our code, it should start by running themainfunction. But we can make our own custom functions as well! Let’s write our first custom function in myFunWithFunctions.ktfile:
fun myFirstFunction(): String { return "I made my first Kotlin function!" }
We’re using the samefunkeyword as before, and we’re giving this function the name ofmyFirstFunction. Notice the : Stringthat comes after the function name; this tells Kotlin that when this function finishes running, it is going to return aStringobject. If we don’t specify that, Kotlin assumes that our function is returningUnit, which is the same thing asvoidin Java. Finally, we use thereturnkeyword to return our string.
This new function we’ve created can now be used in the main function of our program. Here’s the final content of theFunWithFunctions.ktfile:
fun myFirstFunction(): String { return "I made my first Kotlin function!" }
fun main() { val result = myFirstFunction() println(result)
}
Kotlin has support for higher order functions. A function is a higher order function if it can do at least one of the following things:
Accept another function as an argument.
Return a function.
Passing Functions to Other Functions
Let’s examine passing functions into other functions. First, let’s define a function that returns aString:
fun a(): String { return "I can haz functionz!" }
Next, we’ll create a second function that can accept this function as a parameter:
fun b(parameter: () -> String): String { return parameter() }
We can call functionb, passing in functionain our main function:
fun main() { println(b(::a)) }
When functionbruns, it will take functionaas the parameter and execute it, returning the value:
I can haz functionz!
Functions That Return Functions
Let’s talk about the second capability that higher order functions possess: returning other functions. Let’s start off again with our functionafrom before:
fun a(): String { return “I can haz functionz!” }
Next we define a new functioncthat will return the functionawe defined earlier:
fun c(): () -> String { return ::a }
Note that functionchas a return type of() -> String. This is becausecis returning the functionawhich returns aString. Kotlin, being strongly typed, requires us to match our return types correctly. This is different from dynamically typed languages like Ruby, which do not require types to be specified. This might seem like a nuisance at first, but in future episodes we’ll examine how using a strongly typed language like Kotlin actually helps us prevent bugs in our code by using types.
When the functioncexecutes, it returns the functiona, but it does not execute functiona. Let’s see what happens when we call this in the main function:
fun main() { println(c()) }
This will print:
function a (Kotlin reflection is not available)
This is because functionais being directly returned as a function, instead of executing and returning aStringtype. To make it execute, we would have to add two sets of parentheses in the println statement:
fun main() { println(c()()) }
Now the functiona, which is returned by the functionc, will execute and return theStringvalue:
I can haz functionz!
This prints out correctly because now we’re calling c which returns a function, then calling that returned function (c is returning a).
To help clarify what’s going on here, let’s write our main function a different way:
fun main() { val functionA = c() println(functionA)
}
Note the lack of parentheses aroundfunctionAin theprintlnstatement. Kotlin will print this out again:
function a (Kotlin reflection is not available)
We can add parentheses tofunctionAin theprintlnstatement to makefunctionAexecute:
fun main() { val functionA = c() println(functionA())
}
Now we get the result we wanted:
I can haz functionz!
Higher order functions are a key component of functional programming, as it allows us to build up our program by connecting functions to functions. In future episodes we’ll start to examine how this becomes useful especially as we later learn aboutfunction composition, which allows us to write software that is easier to comprehend.
Join me next week onKotlin Thursdayswhen I talk about anonymousfunctionsandlambdas!
Kotlin Town
6 members
Description
Interested in Kotlin? Are you a practitioner?
Kotlin is a statically typed language that runs on JVM that may compile to JavaScript source code or use the LLVM compiler infrastructure. Since then, it’s grown exponentially in popularity. In 2017, Google officially backed Kotlin as the official language for Android.
And that's just the beginning! Join us here at Kotlin Town and be a part of the evolution of this exciting new language.
Kotlin Thursdays - Introduction to Functional Programming in Kotlin Part 1
by Amanda Hinchman-Dominguez
Apr 11, 2019
Resources
Introduction
Welcome to Kotlin Thursdays! This week I’m starting a series on functional programming with Kotlin. Functional programming is something I’m passionate about, and Kotlin has some great functional programming support! Functional programming can lead to code that is easier to think about, has fewer bugs and is easier to test.
What better way to dive into functional programming than to learn about functions! It might help to think of functions as “mini-programs”. Functions allow us to write some code once and then use that code multiple times throughout the rest of our program.
The Main Function
To make a Kotlin program, we need to make a function to “kickstart” our program. This function is called the
main
function. To create themain
function, let’s make a file calledFunWithFunctions.kt
and write the following code in it:We can compile this into a jar file that we can run with the following command on our terminal:
Then we can run the program with the following command:
For those not familiar, a jar file is how Java Virtual Machine programs are packaged into programs that we can easily run. Kotlin, like Java, uses the Java Virtual Machine to run.
Kotlin knows that when we run our code, it should start by running the
main
function. But we can make our own custom functions as well! Let’s write our first custom function in myFunWithFunctions.kt
file:We’re using the same
fun
keyword as before, and we’re giving this function the name ofmyFirstFunction
. Notice the: String
that comes after the function name; this tells Kotlin that when this function finishes running, it is going to return aString
object. If we don’t specify that, Kotlin assumes that our function is returningUnit
, which is the same thing asvoid
in Java. Finally, we use thereturn
keyword to return our string.This new function we’ve created can now be used in the main function of our program. Here’s the final content of the
FunWithFunctions.kt
file:Now we can compile and run it:
Higher Order Functions
Kotlin has support for higher order functions. A function is a higher order function if it can do at least one of the following things:
Passing Functions to Other Functions
Let’s examine passing functions into other functions. First, let’s define a function that returns a
String
:Next, we’ll create a second function that can accept this function as a parameter:
We can call function
b
, passing in functiona
in our main function:When function
b
runs, it will take functiona
as the parameter and execute it, returning the value:Functions That Return Functions
Let’s talk about the second capability that higher order functions possess: returning other functions. Let’s start off again with our function
a
from before:Next we define a new function
c
that will return the functiona
we defined earlier:Note that function
c
has a return type of() -> String
. This is becausec
is returning the functiona
which returns aString
. Kotlin, being strongly typed, requires us to match our return types correctly. This is different from dynamically typed languages like Ruby, which do not require types to be specified. This might seem like a nuisance at first, but in future episodes we’ll examine how using a strongly typed language like Kotlin actually helps us prevent bugs in our code by using types.When the function
c
executes, it returns the functiona
, but it does not execute functiona
. Let’s see what happens when we call this in the main function:This will print:
This is because function
a
is being directly returned as a function, instead of executing and returning aString
type. To make it execute, we would have to add two sets of parentheses in the println statement:Now the function
a
, which is returned by the functionc
, will execute and return theString
value:This prints out correctly because now we’re calling c which returns a function, then calling that returned function (c is returning a).
To help clarify what’s going on here, let’s write our main function a different way:
Note the lack of parentheses around
functionA
in theprintln
statement. Kotlin will print this out again:We can add parentheses to
functionA
in theprintln
statement to makefunctionA
execute:Now we get the result we wanted:
Higher order functions are a key component of functional programming, as it allows us to build up our program by connecting functions to functions. In future episodes we’ll start to examine how this becomes useful especially as we later learn about function composition, which allows us to write software that is easier to comprehend.
Join me next week on Kotlin Thursdays when I talk about anonymous functions and lambdas!