<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Matt Moore on Medium]]></title>
        <description><![CDATA[Stories by Matt Moore on Medium]]></description>
        <link>https://medium.com/@matt-moore?source=rss-d2882f0865a2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*Hw7Q7T25Si2QsE2mofPVmQ.jpeg</url>
            <title>Stories by Matt Moore on Medium</title>
            <link>https://medium.com/@matt-moore?source=rss-d2882f0865a2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 07:15:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@matt-moore/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Kotlin JNI for Native Code]]></title>
            <link>https://matt-moore.medium.com/kotlin-jni-for-native-code-835e93af7ddf?source=rss-d2882f0865a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/835e93af7ddf</guid>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Matt Moore]]></dc:creator>
            <pubDate>Sun, 16 Jun 2019 22:16:02 GMT</pubDate>
            <atom:updated>2019-08-17T23:20:18.268Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to call native code from Kotlin.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rbgbk4D5wajHA079eAayZw.jpeg" /></figure><p>I’ve become a fan of TensorFlow for building machine learning models. But TensorFlow is currently not available for Kotlin. There is a Java wrapper that has been built but it doesn’t support the full TensorFlow library and requires an additional inter-oping with Java. I wanted a Kotlin wrapper directly over the C++ TensorFlow library.</p><p>I decided to start building it out myself. To that end, I needed to get JNI up and running within Kotlin. JNI allows us to access native libraries from within JVM languages, including Kotlin. Searching around the internet didn’t turn up a ton of info on using JNI with Kotlin specifically, so I’m sharing my own findings tinkering with it.</p><h3>High-Level Overview</h3><ol><li>First, we write our Kotlin code that calls the C/C++ code and compile it.</li><li>Create a C/C++ header file for JNI to know how to talk to the native library.</li><li>Then, we build our C/C++ code.</li><li>Finally, we can run the Kotlin program with an option pointing to the C/C++ library we want to call.</li></ol><h3>The Kotlin Code</h3><p>Here’s an example of how to build a basic Kotlin class that can call C code:</p><pre>class NativeSample {<br>  init {<br>    System.loadLibrary(&quot;hello&quot;)<br>  }</pre><pre>  external fun sayHello()<br>}</pre><p>We’ll save that in a text file called NativeSample.kt. Now, let’s create another file to run our main function in Main.kt:</p><pre>fun main() {<br>  NativeSample().sayHello()<br>}</pre><p>Now we can compile these two files to NativeSample.jar:</p><pre>kotlinc-jvm -include-runtime -d NativeSample.jar *.kt</pre><h3>The C Code</h3><p>Now let’s create the C code that our Kotlin class will call. First, we’ll create a file called hello.c:</p><pre>#include &lt;stdio.h&gt;<br>#include &quot;NativeSample.h&quot;</pre><pre>JNIEXPORT void JNICALL Java_NativeSample_sayHello(JNIEnv *env, jobject obj) {<br>  printf(&quot;Hello World!\n&quot;);<br>  return;<br>}</pre><p>You’ll notice the #include &quot;NativeSample.h&quot; added to the second line of hello.c. We will need to create that header file. Note that the line that starts with JNIEXPORT has Java_NativeSample_sayHello. This needs to match our class and method in the NativeSample.kt file. It starts with Java, then follows with the name of our class NativeSample. Next it contains the method name sayHello.</p><p>Next, make a new text file NativeSample.h and add this to it:</p><pre>#include &lt;jni.h&gt;</pre><pre>#ifndef _Included_NativeSample<br>#define _Included_NativeSample<br>#ifdef __cplusplus<br>extern &quot;C&quot; {<br>#endif</pre><pre>JNIEXPORT void JNICALL Java_NativeSample_sayHello(JNIEnv *, jobject);</pre><pre>#ifdef __cplusplus<br>}<br>#endif<br>#endif</pre><p>Now we’re ready to compile our C code:</p><pre>gcc hello.c -o libhello.so -shared -fPIC -I /usr/lib/jvm/java-12-openjdk-amd64/include -I /usr/lib/jvm/java-12-openjdk-amd64/include/linux</pre><p>You’ll need to replace /usr/lib/jvm/java-12-openjdk-amd64 with your own JDK path. The above command will produce a file called libhello.so. This is our C library that prints Hello World!.</p><h3>Running The Program</h3><p>Now we’re ready to run Kotlin code we compiled earlier to call our C program:</p><pre>java -jar NativeSample.jar</pre><p>You should see:</p><pre>Hello World!</pre><h3>Conclusion</h3><p>You’ve now successfully compiled a Kotlin JVM program that calls a C library! This process is what I’m using to build out a Kotlin API around the C++ TensorFlow library. Stay tuned as I continue my saga of bringing TensorFlow to Kotlin!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=835e93af7ddf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Functors, Applicatives And Monads. Part 1 of 3]]></title>
            <link>https://matt-moore.medium.com/kotlin-functors-applicatives-and-monads-part-1-of-3-ba399a3a2247?source=rss-d2882f0865a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba399a3a2247</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[applicative]]></category>
            <category><![CDATA[functor]]></category>
            <category><![CDATA[monads]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Matt Moore]]></dc:creator>
            <pubDate>Sun, 12 May 2019 21:03:53 GMT</pubDate>
            <atom:updated>2019-05-12T21:03:53.068Z</atom:updated>
            <content:encoded><![CDATA[<h4>Spoiler alert: Functors are classes with properties you can use map with. They’re a building block of monads.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3njQKq_ZS2CGqbpRWVMUNA.jpeg" /></figure><p>In the functional programming world, lots of folks have heard about monads. Monad is a funny word and it’s used often in more advanced functional programming. I wanted to set out to explain monads, but before I do that, let’s talk about functors.</p><p>Functor is a funny word too. I want to talk about functors because they are a precursor to monads. <strong>A functor is any class that holds data and can be mapped over</strong>.</p><h3>Values</h3><p>When dealing with values, we can apply a function to them. For example, I can create a function called inc which will increment a value by 1:</p><pre>fun inc(value: Int): Int = value + 1</pre><p>Then I can use it like this:</p><pre>val result = inc(1)</pre><p>result will equal 2.</p><h3>Functors: A Class Wrapped Around a Value</h3><p><strong>A functor is any class that defines </strong><strong>map</strong>. Let’s create a class that implements map:</p><pre>class Functor&lt;T&gt;(val value: T) {<br>    fun map(function: (T) -&gt; T): Functor&lt;T&gt; {<br>        return Functor(function(value))<br>    }<br>}</pre><p>The Functor class:</p><ul><li>Accepts a value.</li><li>Defines a map function. The map function accepts a higher-order function and applies it to the value Functor holds. map then returns another Functor storing the result in the new Functor.value.</li></ul><p>Let’s instantiate the Functor class, passing in our inc function:</p><pre>Functor(1).map(::inc)</pre><p>Functor.map returns another functor with the value increased by 1:</p><pre>Functor(2)</pre><p>I could also pass a lambda to the functor’s map:</p><pre>Functor(1).map { it + 1 }</pre><h3>Chaining</h3><p>Because Functor.map returns another Functor with the result of the function passed to map I can chain multiple map functions together:</p><pre>Functor(1).map(::inc).map(::inc)</pre><p>Resulting in:</p><pre>Functor(3)</pre><h3>Why Are Functors Useful?</h3><p><strong>One reason functors are useful because they let us use map with collections, replacing for loops</strong>. A collection can contain multiple values and can be mapped over. Let’s say I have a list of books in Kotlin, and I want to get the author for each book. First let’s create data classes for book and author:</p><pre>data class Author(val firstName: String, val lastName: String)</pre><pre>data class Book(val title: String, val author: Author)</pre><p>Next we’ll create a list of books containing their authors:</p><pre>val books = listOf(<br>  Book(&quot;Microservices Architecture&quot;, Author(&quot;Chris&quot;, &quot;Richardson&quot;)),<br>  Book(&quot;Kotlin in Action&quot;, Author(&quot;Dmitry&quot;, &quot;Jemerov&quot;))<br>)</pre><p>If I want to iterate through the list of books to get all the authors, I can do this:</p><pre>books.map { it.author }</pre><p>I could also use the filter function to find the book “Kotlin in Action”, and get its author:</p><pre>books.filter { it.title == &quot;Kotlin in Action&quot; }<br>     .map { &quot;${it.author.firstName} ${it.author.lastName}&quot; }</pre><p>In each of these cases, I’m using a collection to store the book and then I’m using map or filter to iterate through the collection of books. <strong>List is a functor because </strong><strong>List implements the </strong><strong>map function</strong>. map applies a function to the values in the list, and returns the results in a new list.</p><p><strong>Functors are also important because they are a building block for applicatives and monads</strong>. I’ll examine applicatives in part 2 and finally monads in part 3.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba399a3a2247" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Kafka]]></title>
            <link>https://medium.com/kotlin-thursdays/getting-started-with-kafka-9cb4c7878290?source=rss-d2882f0865a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cb4c7878290</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[kotlin-thursdays]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Matt Moore]]></dc:creator>
            <pubDate>Mon, 29 Apr 2019 18:22:27 GMT</pubDate>
            <atom:updated>2019-04-30T01:19:45.110Z</atom:updated>
            <content:encoded><![CDATA[<h4>Kafka with Docker on your local machine</h4><p>I’ve set up Kafka on Docker and Docker-Compose for myself and other folks to use on their local laptops.</p><h3>Installing Docker</h3><p>To get started, you’ll first need to download and install Docker.</p><ul><li>Create an account at: <a href="https://hub.docker.com/editions/community/docker-ce-desktop-mac">https://hub.docker.com/editions/community/docker-ce-desktop-mac</a></li><li>Download and install Docker Community Edition</li></ul><p>Now that you’re signed in, head to your terminal and check that the CLI is installed with:</p><pre>docker version</pre><h3>Running Kafka in Docker</h3><p>Next, git clone my <a href="https://github.com/Kotlin-Thursdays/kafka-standalone.git">kafka-standalone</a> docker setup.</p><pre>git clone <a href="https://github.com/Kotlin-Thursdays/kafka-standalone.git">https://github.com/Kotlin-Thursdays/kafka-standalone.git</a><br>cd kafka-standalone<br>docker-compose up -d</pre><p>This will download and spin up the necessary docker containers to run kafka on your local laptop. This may take a few minutes, depending on your internet connection and laptop speed. When it’s finished, you can check that it’s running correctly:</p><pre>docker-compose ps</pre><h3>Creating A Topic</h3><p>You can create a new topic in Kafka to send and receive messages on:</p><pre>docker-compose run --rm kafka-client /kafka/bin/kafka-topics.sh --zookeeper zookeeper:2181 --create --topic messages --partitions 1 --replication-factor 1</pre><h3>Sending Messages on Kafka</h3><p>You can spin up a producer to send messages with:</p><pre>docker-compose run --rm kafka-client /kafka/bin/kafka-console-producer.sh --broker-list broker:29092 --topic messages</pre><p>Once that spins up, you should be able to type messages and send them by hitting the enter key:</p><pre>&gt; This is a test message</pre><h3>Receiving Messages on Kafka</h3><p>You can spin up a consumer to receive messages:</p><pre>docker-compose run --rm kafka-client /kafka/bin/kafka-console-consumer.sh --bootstrap-server broker:29092 --topic messages --from-beginning</pre><p>You should see your message show up:</p><pre>This is a test message</pre><p>That’s about it! You’re ready to start building applications with Kafka!</p><h3>Building an Order System with Kotlin, Kafka, and Domain-Driven Design</h3><p>Kafka is a scalable event-driven message system able to communicate in intense and complex systems. In the next post, we’ll be demonstrating the power of Kafka by building an online-ordering system!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rdlfz7ag6DbFcjs21MdvWg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cb4c7878290" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kotlin-thursdays/getting-started-with-kafka-9cb4c7878290">Getting Started with Kafka</a> was originally published in <a href="https://medium.com/kotlin-thursdays">Kotlin Thursdays</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional Programming in Kotlin Part 2: Functions as Data with Anonymous Functions & Lambdas]]></title>
            <link>https://medium.com/kotlin-thursdays/functional-programming-in-kotlin-part-2-functions-as-data-with-anonymous-functions-lambdas-b9947e97a6d7?source=rss-d2882f0865a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9947e97a6d7</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[kotlin-thursdays]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[kotlin-beginners]]></category>
            <dc:creator><![CDATA[Matt Moore]]></dc:creator>
            <pubDate>Thu, 11 Apr 2019 16:01:02 GMT</pubDate>
            <atom:updated>2019-04-11T16:03:03.359Z</atom:updated>
            <content:encoded><![CDATA[<h3>Functional Programming in Kotlin Part 2</h3><h4>Functions as Data Using Lambdas</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*HvYGvUVk2xur_eF_ooN8aA.png" /></figure><h3>Resources</h3><ul><li><strong>Higher-Order Functions and Lambdas:</strong> <a href="https://kotlinlang.org/docs/reference/lambdas.html">https://kotlinlang.org/docs/reference/lambdas.html</a></li><li><strong>FP in Kotlin Part 1:</strong> <a href="https://medium.com/kotlin-thursdays/functional-programming-in-kotlin-part-1-functions-c025a6b97264">https://medium.com/kotlin-thursdays/functional-programming-in-kotlin-part-1-functions-c025a6b97264</a></li></ul><h3>Introduction</h3><p><a href="https://medium.com/kotlin-thursdays/functional-programming-in-kotlin-part-1-functions-c025a6b97264">Last week</a>, we went over higher order functions in Kotlin. We learned how higher order functions can accept functions as parameters and are also able to return functions. This week, we will take a look at <strong>lambdas</strong>. <strong>Lambdas are another type of function and they are very popular in the functional programming world</strong>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FAjfVd3MpqOY%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DAjfVd3MpqOY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FAjfVd3MpqOY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b33aabcc27149a6924abf1dfd151d6a/href">https://medium.com/media/5b33aabcc27149a6924abf1dfd151d6a/href</a></iframe><h3>Logic &amp; Data</h3><p>Computer programs are made up of two parts: <strong>logic</strong> and <strong>data</strong>. Usually, <strong>logic is described in functions</strong> and <strong>data is passed to those functions</strong>. The functions do things with the data, and return a result. When we write a function we would typically create a <strong>named function</strong>. As we saw last week, this is a typical named function:</p><pre>fun hello(name: String): String {<br>  return &quot;Hello, $name&quot;<br>}</pre><p>Then you can call this function:</p><pre>fun main() {<br>  println(hello(&quot;Matt&quot;))<br>}</pre><p>Which gives us the result:</p><pre>Hello, Matt</pre><h3>Functions as Data</h3><p>There is a concept in the functional programming world where <strong>functions are treated as data</strong>. <strong>Lambdas</strong> (functions as data) can do the same thing as named functions, but <strong>with lambdas, the content of a given function can be passed directly into other functions</strong>. A lambda can also be assigned to a variable as though it were just a value.</p><h3>Lambda Syntax</h3><p>Lambdas are similar to named functions but lambdas do not have a name and the lambda syntax looks a little different. Whereas a function in Kotlin would look like this:</p><pre>fun hello() {<br>  return &quot;Hello World&quot;<br>}</pre><p>The lambda expression would look like this:</p><pre>{ &quot;Hello World&quot; }</pre><p>Here is an example with a parameter:</p><pre>fun(name: String) {<br>  return &quot;Hello, ${name}&quot;<br>}</pre><p>The lambda version:</p><pre>{ name: String -&gt; &quot;Hello, $name&quot; }</pre><p>You can call the lambda by passing the parameter to it in parentheses after the last curly brace:</p><pre>{ name: String -&gt; &quot;Hello, $name&quot; }(&quot;Matt&quot;)</pre><p>It’s also possible to assign a lambda to a variable:</p><pre>val hello = { name: String -&gt; &quot;Hello, $name&quot; }</pre><p>You can then call the variable the lambda has been assigned to, just as if it was a named function:</p><pre>hello(&quot;Matt&quot;)</pre><p>Lambdas provide us with a convenient way to pass logic into other functions without having to define that logic in a named function. This is very useful when processing lists or arrays of data. We’ll take a look at processing lists with lambdas in the next post!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9947e97a6d7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kotlin-thursdays/functional-programming-in-kotlin-part-2-functions-as-data-with-anonymous-functions-lambdas-b9947e97a6d7">Functional Programming in Kotlin Part 2: Functions as Data with Anonymous Functions &amp; Lambdas</a> was originally published in <a href="https://medium.com/kotlin-thursdays">Kotlin Thursdays</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional Programming in Kotlin Part 1: Functions]]></title>
            <link>https://medium.com/kotlin-thursdays/functional-programming-in-kotlin-part-1-functions-c025a6b97264?source=rss-d2882f0865a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c025a6b97264</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[kotlin-thursdays]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[higher-order-function]]></category>
            <dc:creator><![CDATA[Matt Moore]]></dc:creator>
            <pubDate>Thu, 28 Mar 2019 16:47:15 GMT</pubDate>
            <atom:updated>2019-04-04T23:05:43.958Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kotlin Functional Programming: Higher Order Functions!</h3><h4>An introduction to functional programming in Kotlin with a look at higher order functions.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*3IT8_6dh3Uh25t01mqTj-Q.jpeg" /></figure><h3>Resources</h3><ul><li><strong>Higher-Order Functions and Lambdas:</strong> <a href="https://kotlinlang.org/docs/reference/lambdas.html">https://kotlinlang.org/docs/reference/lambdas.html</a></li></ul><h3>Introduction</h3><p>Welcome to <strong><em>Kotlin Thursdays</em></strong>! 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.</p><p>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.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fw9_RNbzb_5s%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dw9_RNbzb_5s&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fw9_RNbzb_5s%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ab5dc3b7f2e6f1db386012b25ec403a/href">https://medium.com/media/1ab5dc3b7f2e6f1db386012b25ec403a/href</a></iframe><h3>The Main Function</h3><p>To make a Kotlin program, we need to make a function to “kickstart” our program. This function is called the main function. To create the main function, let’s make a file called FunWithFunctions.kt and write the following code in it:</p><pre>fun main() {<br>  println(“Hello World!”)<br>}</pre><p>We can compile this into a jar file that we can run with the following command on our terminal:</p><pre>kotlinc-jvm FunWithFunctions.kt -include-runtime -d functions.jar</pre><p>Then we can run the program with the following command:</p><pre>java -jar functions.jar</pre><p>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.</p><p>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 my FunWithFunctions.kt file:</p><pre>fun myFirstFunction(): String {<br>  return &quot;I made my first Kotlin function!&quot;<br>}</pre><p>We’re using the same fun keyword as before, and we’re giving this function the name of myFirstFunction. Notice the : String that comes after the function name; this tells Kotlin that when this function finishes running, it is going to return a String object. If we don’t specify that, Kotlin assumes that our function is returning Unit, which is the same thing as void in Java. Finally, we use the return keyword to return our string.</p><p>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:</p><pre>fun myFirstFunction(): String {<br>  return &quot;I made my first Kotlin function!&quot;<br>}</pre><pre>fun main() {<br>  val result = myFirstFunction()<br>  println(result)<br>}</pre><p>Now we can compile and run it:</p><pre>kotlinc-jvm FunWithFunctions.kt -include-runtime -d functions.jar<br>java -jar functions.jar</pre><h3>Higher Order Functions</h3><p>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:</p><ul><li>Accept another function as an argument.</li><li>Return a function.</li></ul><h3>Passing Functions to Other Functions</h3><p>Let’s examine passing functions into other functions. First, let’s define a function that returns a String:</p><pre>fun a(): String {<br>  return &quot;I can haz functionz!&quot;<br>}</pre><p>Next, we’ll create a second function that can accept this function as a parameter:</p><pre>fun b(parameter: () -&gt; String): String {<br>  return parameter()<br>}</pre><p>We can call function b, passing in function a in our main function:</p><pre>fun main() {<br>  println(b(::a))<br>}</pre><p>When function b runs, it will take function a as the parameter and execute it, returning the value:</p><pre>I can haz functionz!</pre><h3>Functions That Return Functions</h3><p>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:</p><pre>fun a(): String {<br>  return “I can haz functionz!”<br>}</pre><p>Next we define a new function c that will return the function a we defined earlier:</p><pre>fun c(): () -&gt; String {<br>  return ::a<br>}</pre><p>Note that function c has a return type of () -&gt; String. This is because c is returning the function a which returns a String. 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.</p><p>When the function c executes, it returns the function a, but it does not execute function a. Let’s see what happens when we call this in the main function:</p><pre>fun main() {<br>  println(c())<br>}</pre><p>This will print:</p><pre>function a (Kotlin reflection is not available)</pre><p>This is because function a is being directly returned as a function, instead of executing and returning a String type. To make it execute, we would have to add two sets of parentheses in the println statement:</p><pre>fun main() {<br>  println(c()())<br>}</pre><p>Now the function a, which is returned by the function c, will execute and return the String value:</p><pre>I can haz functionz!</pre><p>This prints out correctly because now we’re calling c which returns a function, then calling that returned function (c is returning a).</p><p>To help clarify what’s going on here, let’s write our main function a different way:</p><pre>fun main() {<br>  val functionA = c()<br>  println(functionA)<br>}</pre><p>Note the lack of parentheses around functionA in the println statement. Kotlin will print this out again:</p><pre>function a (Kotlin reflection is not available)</pre><p>We can add parentheses to functionA in the println statement to make functionA execute:</p><pre>fun main() {<br>  val functionA = c()<br>  println(functionA())<br>}</pre><p>Now we get the result we wanted:</p><pre>I can haz functionz!</pre><p>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 <strong>function composition</strong>, which allows us to write software that is easier to comprehend.</p><p>Join me next week on <strong><em>Kotlin Thursdays</em></strong> when I talk about anonymous <strong>functions</strong> and <strong>lambdas</strong>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c025a6b97264" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kotlin-thursdays/functional-programming-in-kotlin-part-1-functions-c025a6b97264">Functional Programming in Kotlin Part 1: Functions</a> was originally published in <a href="https://medium.com/kotlin-thursdays">Kotlin Thursdays</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>