<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="http://nomisrev.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="http://nomisrev.github.io/" rel="alternate" type="text/html" /><updated>2026-05-21T08:47:17+00:00</updated><id>http://nomisrev.github.io/feed.xml</id><title type="html">nomisRev</title><subtitle>Personal blog to share some snippets, thoughts, blogs or interessting discussion from Kotlin Slack</subtitle><author><name>Simon Vergauwen</name></author><entry><title type="html">Opinionated Ktor Services</title><link href="http://nomisrev.github.io/opinionated-ktor-services/" rel="alternate" type="text/html" title="Opinionated Ktor Services" /><published>2026-05-21T00:00:00+00:00</published><updated>2026-05-21T00:00:00+00:00</updated><id>http://nomisrev.github.io/opinionated-ktor-services</id><content type="html" xml:base="http://nomisrev.github.io/opinionated-ktor-services/"><![CDATA[<p>Today I gave a talk at KotlinConf 2026 in Munich about “Opinionated Ktor Services”. 
In this talk, I shared my experience and opinions on how to build robust, maintainable, and scalable services using Ktor and the Kotlin ecosystem.</p>

<p>Building services with Ktor is a lot of fun, but because it is so flexible, it can sometimes be hard to decide on a structure or which libraries to use.
This talk aims to provide a set of “opinions” that have worked well for me and the teams I’ve worked with.</p>

<h3 id="resources">Resources</h3>

<ul>
  <li><a href="https://github.com/nomisRev/ktor-quickstart">Ktor Quickstart</a> - Ktor Quickstart template</li>
  <li><a href="https://ktor.io/docs/">Ktor Documentation</a> - The official Ktor documentation.</li>
  <li><a href="https://kotlinconf.com">KotlinConf 2026</a> - The conference website.</li>
</ul>

<h3 id="slides">Slides</h3>

<p>The slides for the talk can be found here: <a href="https://speakerdeck.com/nomisrev/opinionated-ktor-services">Opinionated Ktor Services - Slides</a> (Coming soon)</p>

<h3 id="video">Video</h3>

<p>The recording of the talk will be available on the <a href="https://www.youtube.com/@Kotlin">Kotlin YouTube channel</a> later this year.</p>

<hr />

<p>Thank you to everyone who attended the talk! It was great to meet so many of you in Munich.
If you have any questions, feel free to reach out to me on the <a href="https://slack-chats.kotlinlang.org/">Kotlin Slack</a>, <a href="https://twitter.com/vergauwen_simon">Twitter</a>, <a href="https://bsky.app/profile/vergauwensimon.bsky.social">BlueSky</a> or <a href="https://www.linkedin.com/in/vergauwensimon/">LinkedIn</a>.</p>]]></content><author><name>Simon Vergauwen</name></author><category term="Kotlin" /><category term="Ktor" /><category term="Microservices" /><category term="KotlinConf" /><summary type="html"><![CDATA[Today I gave a talk at KotlinConf 2026 in Munich about “Opinionated Ktor Services”. In this talk, I shared my experience and opinions on how to build robust, maintainable, and scalable services using Ktor and the Kotlin ecosystem.]]></summary></entry><entry><title type="html">Arrow 2.0’s Trajectory</title><link href="http://nomisrev.github.io/arrows-2-0-trajectory/" rel="alternate" type="text/html" title="Arrow 2.0’s Trajectory" /><published>2023-04-16T00:00:00+00:00</published><updated>2023-04-16T00:00:00+00:00</updated><id>http://nomisrev.github.io/arrows-2-0-trajectory</id><content type="html" xml:base="http://nomisrev.github.io/arrows-2-0-trajectory/"><![CDATA[<p>This blog post is an improved version of the transcription of the presentation I gave at KotlinConf 2023.
It discusses the 10-year history of <a href="https://arrow-kt.io">Arrow</a>, all the way from the first commit to the current state of the library.
It also discusses the future of Functional Programming in <a href="https://kotlinlang.org">Kotlin</a>, and the challenges OSS projects face.</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.001.png" alt="slide-001" /></p>

<p>Good morning everyone,</p>

<p>I hope you all had a great trip to Amsterdam and are well-rested for this exciting conference.
I am thrilled to be here today to discuss Kotlin, Open-Source, and Functional Programming.</p>

<p>Thank you all for coming to my talk about Arrow’s trajectory towards 2.0.</p>

<p>Before we dive into the main topic, let me briefly introduce myself. My name is Simon.</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.002.png" alt="slide-002" /></p>

<p>I have been working with Kotlin for the past eight years, since 2015, and I am a fanatic open-source developer.</p>

<p>Mostly active on GitHub and over the past five years, my primary focus has been on Arrow, but I also contribute to other projects and organisations.</p>

<p>Currently, I work as a Principal Engineer at <a href="https://www.47deg.com">Xebia Functional</a>, previously known as 47 Degrees.</p>

<p>My favorite place to engage with the community is the <a href="https://slack-chats.kotlinlang.org/c/arrow">Kotlin Slack</a>, but you can also find me on <a href="https://fosstodon.org/@vergauwen_simon">Mastodon</a> and <a href="https://twitter.com/vergauwen_simon">Twitter</a>. I exclusively discuss Kotlin, with a focus on Arrow and back-end related topics.</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.003.png" alt="slide-003" /></p>

<p>During this talk, I plan to cover five topics.
Firstly, I will shed light on the history of Arrow and the reasoning behind some decisions made in the past. As we dive into this topic, I will also discuss the complexity of functional programming from a Kotlin perspective. While these opinions are my own, I believe they are shared by many in the Kotlin and Arrow community.</p>

<p>Next, I will share my thoughts on the importance of embracing the language and the ecosystem. A uniform and cohesive ecosystem of libraries that work well together is crucial not only for productivity and collaboration within the community, but also for the success of the language.</p>

<p>In addition, I will discuss one of the hardest aspects of open-source software - evolving APIs and libraries. While it can be frustrating and expensive to break code, sometimes it’s necessary in the path towards success.</p>

<p>Lastly, I will mention other projects in the ecosystem and highlight the community in and around Arrow.</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.004.png" alt="slide-004" /></p>

<p>To understand the history of Arrow, we need to take a big jump back to a time before Kotlin was on my radar. In 2013, Mario Arias created funKtionale. Developers working in Scala with Spring wanted to use Kotlin’s seamless interoperability with Java. However, they quickly realized that Kotlin lacked a set of features they had grown used to in Scala. This led to the creation of funKtionale, which aimed to solve this problem.</p>

<p>Fast-forward to 2017, a Spanish community named FineCinnamon created a learning project called Katz, heavily inspired by the Typelevel ecosystem in Scala. However, it quickly evolved and changed its name to Kategory to become its own entity as it grew larger over time.</p>

<p>Around the same time, I was also on a learning adventure and created Optikal, an Optics library in Kotlin inspired by Monocle from Scala. After I made the project public, the Kategory maintainers approached me and invited me to the Lambda World conference, where they asked me to join the Kategory efforts. Excited by the opportunity to join forces, I agreed.</p>

<p>Soon after, Mario from funKtionale joined us, and we all merged our efforts to prevent conflicting libraries in the community. To avoid imposing a name, we created a new open-source organization called Arrow.</p>

<p>Arrow’s goal is to facilitate <strong>uniform and idiomatic</strong> functional programming <strong>for everyone</strong> in Kotlin, preventing fragmentation and competing libraries.</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.005.png" alt="slide-005" /></p>

<p>All of this happened during what I refer to as the pre-0.12.x era, which heavily relied on Typeclasses and Higher Kinded Types - two features that don’t exist in Kotlin but are available in Scala.</p>

<p>While I don’t want to delve too deeply into these technical concepts, I would like to briefly show how they were used in Arrow pre-0.12.x to give you an idea of how far we’ve come.</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.006.png" alt="slide-006" /></p>

<p>It’s clear that in the early days, Arrow code looked quite foreign to many Kotlin developers, especially those coming from a Java background where these features didn’t exist.</p>

<p>It’s worth noting that Kotlin’s Structured Concurrency didn’t exist at the time either.</p>

<p>The heavy use of generics and the <code class="language-plaintext highlighter-rouge">Kind</code> type to emulate Higher Kinded Types made the code look and feel non-idiomatic. The concept of Higher Kinded Types and the <code class="language-plaintext highlighter-rouge">F</code> generic leaked everywhere, as shown in the example of the <code class="language-plaintext highlighter-rouge">ListK</code> wrapper used to wrap a Kotlin <code class="language-plaintext highlighter-rouge">List</code>.</p>

<p>All of this complexity made it challenging for developers to work with these abstractions, particularly since Kotlin didn’t natively support this functionality and relied on tricks and hacks to make it work.</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.007.png" alt="slide-007" /></p>

<p>In this code snippet, we can observe how the <code class="language-plaintext highlighter-rouge">GistsApi</code> is used with <code class="language-plaintext highlighter-rouge">Mono</code> type from Project Reactor.</p>

<p>However, due to the <code class="language-plaintext highlighter-rouge">F</code> abstraction and Higher Kinded Types, we have to use the <code class="language-plaintext highlighter-rouge">fix</code> method to “fix” the Higher Kinded representation to access the resulting <code class="language-plaintext highlighter-rouge">mono</code> value, and finally we can call the code…</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.008.png" alt="slide-008" /></p>

<p>So, what’s the point of all this <code class="language-plaintext highlighter-rouge">F</code> and Higher Kinded Type complexity?</p>

<p><code class="language-plaintext highlighter-rouge">F</code> is often used to write code that is independent of the runtime or framework being used. This allows for higher-level, more abstract code that doesn’t make any assumptions about the <em>effect</em> being used.</p>

<p>However, achieving this level of abstraction required a lot of complexity and obscurity. We had to use tricks and hacks like <code class="language-plaintext highlighter-rouge">Kind</code> and <code class="language-plaintext highlighter-rouge">ListK</code> to work around Kotlin’s lack of support for Higher Kinded Types.
Fortunately, this is now a thing of the past.</p>

<p>With the introduction of KotlinX Structured Concurrency in September 2018, we no longer need to rely on these abstractions to the same extent.
It’s a big step forward that has made our code simpler and easier to understand. But it’s important to remember where we came from and appreciate the progress we’ve made.</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.009.png" alt="slide-009" /></p>

<p>Around 2018-2019, with the announcement and release of Structured Concurrency, we decided to move away from our previous approach and look for new solutions. This led to an overhaul of Arrow, and marked a major milestone with the release of versions 0.12.x and 0.13.x.</p>

<p>In version 0.12.x, we deprecated the use of Higher Kinded Types and Typeclasses, which had powered the machinery in our earlier code examples.</p>

<p>With the release of version 0.13.x, we completely removed these features, and as a result, we were able to support Kotlin Multiplatform in Arrow. This was a significant step forward and demonstrated the benefits of simplifying our code and aligning more closely with the idioms of the language.</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.010.png" alt="slide-010" /></p>

<p>In summary, using Arrow for functional programming in Kotlin originally presented a steep learning curve. It required familiarity with the programming style used in Scala or Haskell, resulting in non-idiomatic code that was difficult to comprehend and explain. This also caused friction with IDEA and other tooling at the time.</p>

<p>Moreover, Arrow’s approach attempted to emulate concepts that were not available in Kotlin, leading to a foreign and complex development experience. This went against one of Arrow’s primary goals: to provide functional programming that is idiomatic and accessible to everyone using Kotlin.</p>

<p>Fortunately, with the popularity of KotlinX Structured Concurrency and Kotlin Coroutines, we sought a solution that seamlessly integrates these technologies with Arrow without compromising any of its features. In the following sections, we will explore how we have achieved this, eliminating complexity and delivering a more elegant and intuitive experience for developers.</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.011.png" alt="slide-011" /></p>

<p>In this updated definition of our <code class="language-plaintext highlighter-rouge">GistsApi</code>, you will notice that all references to <code class="language-plaintext highlighter-rouge">F</code> have disappeared, and we have eliminated our custom <code class="language-plaintext highlighter-rouge">ListK</code> wrapper as well. Now, everything looks like common Kotlin code, and there is no trace of Arrow anymore.</p>

<p>This is because we can leverage the suspend keyword, which takes care of everything that we need, and with the power of Coroutines, we can seamlessly compose or mix-and-match different functional concepts, as we will see shortly.</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.012.png" alt="slide-012" /></p>

<p>As you can see, we have achieved the same goal as before, but in a much simpler way. With a single <code class="language-plaintext highlighter-rouge">GistsApi</code>, we can use it in combination with many runtimes such as Project Reactor, ReactiveX or JDK8 Futures.</p>

<p>Furthermore, building an integration layer with any framework or runtime environment that you need to work with is quite easy and straightforward.</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.013.png" alt="slide-013" /></p>

<p>In the 1.x series of Arrow, we continued to prioritize making the library more Kotlin idiomatic. Building on the success of Structured Concurrency and coroutines, we went all-in on using suspend and domain-specific languages (DSLs).</p>

<p>One challenge with functional APIs is that they often have complex names and signatures, and FP libraries tend to have a large API surface to allow composing all different shapes of functions. This can be overwhelming for developers, as we experienced with Arrow in Kotlin.</p>

<p>To address this, we gathered feedback from the community and through frequently asked question we were able to truly pinpoint the pain points of Arrow. We focused on adopting a DSL-style approach to functional programming, using more idiomatic names and addressing these common pain points.</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.014.png" alt="slide-014" /></p>

<p>This Kotlin code using <a href="https://apidocs.arrow-kt.io/arrow-core/arrow.core/-either/index.html"><code class="language-plaintext highlighter-rouge">Either</code></a> might look familiar if you’ve worked with functional programming languages before.
We use <code class="language-plaintext highlighter-rouge">Either</code> to handle processing a <code class="language-plaintext highlighter-rouge">GithubUser</code>, which can result in either a <code class="language-plaintext highlighter-rouge">ProcessingFailed</code> error or a <code class="language-plaintext highlighter-rouge">ProcessedUser</code>. To wrap these values in the <code class="language-plaintext highlighter-rouge">Either</code> container, we use the <code class="language-plaintext highlighter-rouge">left</code> and <code class="language-plaintext highlighter-rouge">right</code> constructors.</p>

<p>While this approach is perfectly valid, we believe we can make the code even more idiomatic and readable by using DSLs and other Kotlin language features.</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.015.png" alt="slide-015" /></p>

<p>In its DSL form, the same function can be simplified using the <code class="language-plaintext highlighter-rouge">eager</code> function to open the DSL block.
In the 1.x.x series, we still need to distinguish between suspending and non-suspending DSLs using <code class="language-plaintext highlighter-rouge">eager</code>.
And we use the <code class="language-plaintext highlighter-rouge">ensure</code> DSL to check a predicate. If the predicate is not matched, it raises the typed error of <code class="language-plaintext highlighter-rouge">ProcessingFailed</code>.
The <code class="language-plaintext highlighter-rouge">ensure</code> function works similarly to the Kotlin Std require method, but for typed errors instead of exceptions.</p>

<p>With the DSL, we no longer need to explicitly wrap our results in <code class="language-plaintext highlighter-rouge">left</code> or <code class="language-plaintext highlighter-rouge">right</code>.
This is automatically taken care of by the DSL. This same syntax is available for all types in Arrow and can be easily leveraged for your own types.</p>

<p>Interestingly, we can also leverage this same DSL to remove all wrappers altogether, as we’ll see later.
But first, let’s take a look at another example where this pattern is used to simplify APIs.</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.016.png" alt="slide-016" /></p>

<p>In functional programming, transforming every element of a <code class="language-plaintext highlighter-rouge">List</code> using <code class="language-plaintext highlighter-rouge">Either</code>, or a different data type, is typically done using <code class="language-plaintext highlighter-rouge">traverse</code>. Although it is an easy concept to learn, many people still find it challenging to use. This is why the joke “the answer is always traverse” is often mentioned, implying that developers forget to use traverse when it’s needed.</p>

<p>The reason behind this is that we usually associate transforming every element of a <code class="language-plaintext highlighter-rouge">List</code> with the <code class="language-plaintext highlighter-rouge">map</code> function. While every Kotlin developer is familiar with <code class="language-plaintext highlighter-rouge">map</code>, we can’t use it to transform every element of a <code class="language-plaintext highlighter-rouge">List</code> to an <code class="language-plaintext highlighter-rouge">Either</code> since we need an <code class="language-plaintext highlighter-rouge">Either</code> containing a <code class="language-plaintext highlighter-rouge">List</code>. Hence, we need to use <code class="language-plaintext highlighter-rouge">traverse</code> to flip the order of the containers.</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.017.png" alt="slide-017" /></p>

<p>In a DSL style, we no longer need to use <code class="language-plaintext highlighter-rouge">traverse</code> to transform every element of a <code class="language-plaintext highlighter-rouge">List</code> using <code class="language-plaintext highlighter-rouge">Either</code> or another data type.
Instead, we can simply use <code class="language-plaintext highlighter-rouge">map</code> and other standard collection operators.
In the DSL style, we “unwrap” the <code class="language-plaintext highlighter-rouge">Either</code> by using <code class="language-plaintext highlighter-rouge">bind</code>.
This approach works for any data type in Arrow or any custom data type you’ve built a DSL for using Arrow.</p>

<p>By using the APIs that we’re all already familiar with from the Kotlin Std and reducing the API surface of Arrow, we’ve significantly reduced the learning curve of doing FP in Kotlin with Arrow.
This makes it much more user-friendly and less confusing to figure out which API to use.</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.018.png" alt="slide-018" /></p>

<p>We are excited to announce the release of version 1.2.0-RC, which includes the complete API for Arrow 2.0.
This release marks a significant milestone as Arrow 2.0 has been able to shed some of its legacy, obscure, and complex APIs inherited from pre-0.12 era.
The new version is expected to be released later this year, possibly alongside Kotlin 2.0.</p>

<p>The Arrow 2.0 series boasts a small and uniform API that covers all use-cases from the very beginning, with a greatly reduced learning curve.
This makes it much easier for developers to learn and use Arrow. Let’s take a look at some final examples!</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.019.png" alt="slide-019" /></p>

<p>This snippet is very similar to the previous one, but with one key difference: it no longer requires the <code class="language-plaintext highlighter-rouge">eager</code> function.
We no longer have to distinguish between suspending and non-suspending DSLs.</p>

<p>Thanks to Kotlin’s support for DSLs, Arrow DSL functions now have a special color, making them easier to spot and read.</p>

<p>We’re also using Kotlin Contracts in more places to take advantage of the Kotlin compiler’s specialized support.
For instance, we’re using <code class="language-plaintext highlighter-rouge">ensureNotNull</code>, which is similar to <code class="language-plaintext highlighter-rouge">requireNotNull</code> from the Kotlin Standard Library, to check a value and smart-cast it to non-null once it’s been verified.</p>

<p>All these features allow Arrow to provide the same semantics you’d expect from functions in the Kotlin Standard Library, making it feel more idiomatic and natural.</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.020.png" alt="slide-020" /></p>

<p>API naming can be a challenging task, and while languages like Haskell have valid reasons to use more obscure API names, this is not the case in Kotlin. 
This has been especially true since post-0.12.0.</p>

<p>Therefore, we have chosen to follow the conventions of the Kotlin Standard Library for our API naming.
In fact, all the names you see here were inspired by Kotlin’s <code class="language-plaintext highlighter-rouge">Result</code> type.
This approach should make the names feel right at home and familiar to anyone who is already accustomed to the Kotlin Std library.</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.021.png" alt="slide-021" /></p>

<p>One of the most exciting features of Arrow’s functional programming in Kotlin is the use of context receivers, which I believe will be a major innovation and a significant quality-of-life improvement for Kotlin developers in general.</p>

<p>With context receivers, we can forget about wrapper types and instead define <em>co-effects</em>.
For example, instead of returning an <code class="language-plaintext highlighter-rouge">Either</code> of <code class="language-plaintext highlighter-rouge">ProcessingFailed</code> or a <code class="language-plaintext highlighter-rouge">ProcessedUser</code> when processing a <code class="language-plaintext highlighter-rouge">GithubUser</code>, we can add a context that can <em>raise</em> a <code class="language-plaintext highlighter-rouge">ProcessingFailed</code> and simply return a <code class="language-plaintext highlighter-rouge">ProcessedUser</code>, without the need for an <code class="language-plaintext highlighter-rouge">Either</code> wrapper.</p>

<p>Furthermore, we can now access our DSL inside the method body without having to open a DSL block like we did before, as all DSLs in Arrow are built on top of the <code class="language-plaintext highlighter-rouge">Raise</code> type.</p>

<p>For example, when we need to <code class="language-plaintext highlighter-rouge">traverse</code> a collection and transform every element, we can simply use <code class="language-plaintext highlighter-rouge">map</code> without even requiring the use of <code class="language-plaintext highlighter-rouge">bind</code>. This is because processing our user now simply returns <code class="language-plaintext highlighter-rouge">ProcessedUser</code>.</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.022.png" alt="slide-022" /></p>

<p>This same DSL approach is applicable to many patterns.</p>

<p>Here are two small examples:</p>

<ul>
  <li>One is for <code class="language-plaintext highlighter-rouge">Resource</code> safety, where we define an <code class="language-plaintext highlighter-rouge">acquire</code> and a <code class="language-plaintext highlighter-rouge">finalizer</code> action in a direct style.</li>
  <li>The other is the <code class="language-plaintext highlighter-rouge">Saga</code> pattern, where we define an <code class="language-plaintext highlighter-rouge">action</code> and a <code class="language-plaintext highlighter-rouge">compensating action</code> also in a direct style.</li>
</ul>

<p>What is so interesting about these DSLs is that they all compose together without ever requiring nesting of wrappers or any special techniques to combine functionalities such as <em>Monad Transformers</em>.</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.023.png" alt="slide-023" /></p>

<p>I mentioned earlier that by reducing the API surface, we were able to decrease the binary size without compromising on features.
This had a drastic effect on the overall size of Arrow!</p>

<p>Before version 0.12.x, the binary size was slightly over 4,1MB. With the 1.0.0 release, we were able to reduce that to just over 3MB.
But with the latest 2.0 version, the binary size is now under 500KB!</p>

<p>This is a really significant improvement because it means that Arrow has a much smaller impact on the size of your projects or libraries.
With such a small API surface and binary size, it’s now even easier to include Arrow in your projects without worrying about the size impact.</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.024.png" alt="slide-024" /></p>

<p>The evolution of Arrow over the past 10 years has demonstrated the importance of iterative API development.
Community feedback and interaction have been critical to this process, allowing us to build a stronger library together.</p>

<p>Learning a new language can be challenging, as you might have experienced.
While you can be productive in Kotlin within days, as we become more familiar with a language, new patterns and techniques emerge, sometimes requiring us to let go of old patterns learned in other languages. For example, the rise of Structured Concurrency led to the removal of Arrow’s <code class="language-plaintext highlighter-rouge">IO</code>, Higher Kinded Types, and Typeclasses.</p>

<p>While these changes are positive, they also come with a downside: breaking existing code.
This a burden I find very heavy to bear, and Arrow worked hard to mitigate the impact of these changes on our users.</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.025.png" alt="slide-025" /></p>

<p>The first and perhaps most obvious way to deal with API changes is through Kotlin’s <code class="language-plaintext highlighter-rouge">Deprecated</code> annotation, which supports the <code class="language-plaintext highlighter-rouge">ReplaceWith</code> parameter.
This parameter enables a library to suggest a new alternative API.
For example, we can use it to recommend the use of the DSL-based <code class="language-plaintext highlighter-rouge">recover</code> method instead of the old <code class="language-plaintext highlighter-rouge">handleErrorWith</code> method.</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.026.png" alt="slide-026" /></p>

<p>When opening the action window in IntelliJ, the deprecated method will suggest automatically refactoring to the suggested alternative API specified in the <code class="language-plaintext highlighter-rouge">ReplaceWith</code> annotation, which can be applied to the entire project.
However, we have found that this approach doesn’t cover all cases and may not always work as intended.
Additionally, it is not well documented and has some edge cases that need to be considered.</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.027.png" alt="slide-027" /></p>

<p>Another promising option for dealing with breaking changes is OpenRewrite, an open-source tool for large-scale automated refactorings developed by Moderne, a revolutionary automated code remediation platform.</p>

<p>Although Kotlin support in OpenRewrite is still experimental, I found it to be very promising and was among the first to use it extensively.
The community and maintainers were extremely friendly and helpful.</p>

<p>Let’s take a closer look at how we can use OpenRewrite to refactor our codebase.</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.028.png" alt="slide-028" /></p>

<p>To set up OpenRewrite, we only need to configure a few things in Gradle.</p>

<p>Firstly, we need to add the OpenRewrite Gradle plugin to our project’s plugin block.</p>

<p>Next, we add a dependency for the rewrite project, which contains the recipes that describe the various refactorings available.</p>

<p>Finally, we can activate specific recipes by including them in our Gradle configuration.
For example, we could activate the recipe for refactoring the <code class="language-plaintext highlighter-rouge">Raise</code> DSL.</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.029.png" alt="slide-029" /></p>

<p>We can then simply run the rewriteRun task from Gradle.</p>

<p>OpenRewrite will process our project and apply the recipes that we have activated.
After the task completes, OpenRewrite will list the processed files and which recipes have been applied to each of them.</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.030.png" alt="slide-030" /></p>

<p>OpenRewrite is a truly powerful tool that allows us to automate large-scale refactorings, making code maintenance and modernization a breeze.</p>

<p>While Kotlin support is still experimental, it’s evolving rapidly, and any issues or bug reports are typically fixed within a day or two. This gives me great hope for the future of this tool.
It’s currently only supported for the JVM and <code class="language-plaintext highlighter-rouge">commonMain</code> sourceSets, so the refactorings cannot be applied to JS and Native sourceSets at the moment.</p>

<p>At the moment, only one recipe has been finished, but more refactorings and improvements are being made. The aim is to ensure that no one will be left behind on older Arrow versions as the community moves towards 2.0.</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.031.png" alt="slide-031" /></p>

<p>Equally important to all these changes is having good documentation.
With this new version of Arrow, we have a brand new website that emphasizes use-cases and industry patterns instead of just explaining how things work.</p>

<p>The previous website and documentation were quite technical, but we have now re-oriented the documentation to better focus on how Arrow can be used and applied in your projects and applications.</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.032.png" alt="slide-032" /></p>

<p>The new Arrow website also provides an extensive migration guide that explains the reasoning behind all changes in detail, as well as what the expected new code should be and why.</p>

<p>This guide can be helpful if you need to do a manual migration or if OpenRewrite or IntelliJ’s ReplaceWith is not working for your project.</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.033.png" alt="slide-033" /></p>

<p>At Arrow, we believe that functional programming should be accessible to everyone in Kotlin.
To make it easier for users to discover and learn about all the libraries that facilitate this, we’ve added a dedicated ecosystem page to the Arrow website.</p>

<p>We also want to encourage developers who are building functional libraries in Kotlin but aren’t yet listed on the page to reach out to us.
By working together, we can create a vibrant community where users can easily find and use the best functional libraries available.</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.034.png" alt="slide-034" /></p>

<p>Before I conclude, I want to express my gratitude to the entire Arrow community.
To all the contributors who have dedicated their time and effort to make Arrow what it is today, to all the users who trust and utilize Arrow in their projects, and to everyone who provided feedback and supported us along the way.
Thank you all for your invaluable contributions and support.</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.035.png" alt="slide-035" /></p>

<p>We’re very active on both Slack and GitHub, and you can find a large portion of the Arrow and functional programming community there.
I invite all of you to join us if you haven’t already and come chat with us.</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.036.png" alt="slide-036" /></p>

<p>Before I wrap up, I’d like to extend my gratitude to Xebia Functional for their continuous support and sponsorship of Arrow throughout the years, and for building the new Arrow website.
If you visit their booth, you can get a discount coupon for Arrow and Kotlin courses provided by Xebia Functional.</p>

<p>Also, you can find me at the Arrow booth, next to the Xebia Functional booth.
I’ll be there for the entire conference and would be more than happy to answer any questions you may have about Arrow, functional programming, or Kotlin.
I hope to see you there!</p>

<hr />

<p><img src="../assets/KotlinConf - Arrow's 2.0 Trajectory/KotlinConf - Arrow's 2.0 Trajectory - Simon.037.png" alt="slide-037" /></p>

<p>Thank you all for attending my talk today. I hope you found it informative and useful.
I also want to thank the organizers for putting together this fantastic conference and for giving me the opportunity to speak to all of you.</p>

<p>Before you leave, please remember to vote for your favorite talks and speakers. Your feedback helps us improve and deliver better content in the future.</p>

<p>And most importantly, I hope you have a great time at KotlinConf! Enjoy the rest of the sessions and have fun networking with other Kotlin enthusiasts. Thank you!</p>

<hr />]]></content><author><name>Simon Vergauwen</name></author><category term="Kotlin" /><category term="OSS" /><category term="Functional Programming" /><category term="Arrow" /><summary type="html"><![CDATA[This blog post is an improved version of the transcription of the presentation I gave at KotlinConf 2023. It discusses the 10-year history of Arrow, all the way from the first commit to the current state of the library. It also discusses the future of Functional Programming in Kotlin, and the challenges OSS projects face.]]></summary></entry><entry><title type="html">Zero downtime deployment with Arrow and Ktor Native</title><link href="http://nomisrev.github.io/graceful-resource-handling-using-structured-concurrency-in-kotlin/" rel="alternate" type="text/html" title="Zero downtime deployment with Arrow and Ktor Native" /><published>2023-02-16T00:00:00+00:00</published><updated>2023-02-16T00:00:00+00:00</updated><id>http://nomisrev.github.io/graceful-resource-handling-using-structured-concurrency-in-kotlin</id><content type="html" xml:base="http://nomisrev.github.io/graceful-resource-handling-using-structured-concurrency-in-kotlin/"><![CDATA[<p>Webinar with Anton Arhipov on functional microservices with Ktor and Kubernetes about zero-downtime deployments.</p>

<p>The code can be found in the <a href="https://github.com/nomisRev/ktor-k8s-zero-downtime">Ktor K8s Zero Downtime</a> repository.</p>

<p><a href="http://www.youtube.com/watch?v=zKrTBH8jqH4" title="Graceful Resource Handling Using Structured Concurrency in Kotlin"><img src="http://img.youtube.com/vi/zKrTBH8jqH4/0.jpg" alt="Graceful Resource Handling Using Structured Concurrency in Kotlin" /></a></p>

<p>Modern programming often requires us to make strong guarantees about how our applications terminate. One way to do this is through the use of structured concurrency, which allows us to reason about parallel processes and how they relate to each other.</p>

<p>In this session, we will learn how to use Arrow’s Resource Domain-Specific Language (DSL) to reason about resource safety in the same way we use structured concurrency to avoid leaking resources. We will also see how this can be combined with KotlinX Coroutines to build complex use cases in a simple and elegant way using Kotlin DSLs.</p>]]></content><author><name>Simon Vergauwen</name></author><category term="Kotlin" /><category term="StructuredConcurrency" /><category term="Resource" /><category term="Kubernetes" /><category term="Microservices" /><summary type="html"><![CDATA[Webinar with Anton Arhipov on functional microservices with Ktor and Kubernetes about zero-downtime deployments.]]></summary></entry><entry><title type="html">Functional Flowing</title><link href="http://nomisrev.github.io/functional-flowing/" rel="alternate" type="text/html" title="Functional Flowing" /><published>2022-11-24T00:00:00+00:00</published><updated>2022-11-24T00:00:00+00:00</updated><id>http://nomisrev.github.io/functional-flowing</id><content type="html" xml:base="http://nomisrev.github.io/functional-flowing/"><![CDATA[<p>KotlinX’s Flow data type is extremely powerful, and offers an API that is quite familiar for functional programmers.
This talk will showcase how we can leverage KotlinX Flow to describe powerful programs, and build pipelines to transform and manipulate data in an efficient streaming way.</p>

<p><a href="http://www.youtube.com/watch?v=Mj9B0rhN1RE" title="Functional Flowing"><img src="http://img.youtube.com/vi/Mj9B0rhN1RE/0.jpg" alt="Functional Flowing" /></a></p>]]></content><author><name>Simon Vergauwen</name></author><category term="Kotlin" /><category term="KotlinX" /><category term="Flow" /><category term="Streaming" /><summary type="html"><![CDATA[KotlinX’s Flow data type is extremely powerful, and offers an API that is quite familiar for functional programmers. This talk will showcase how we can leverage KotlinX Flow to describe powerful programs, and build pipelines to transform and manipulate data in an efficient streaming way.]]></summary></entry><entry><title type="html">Graceful Shutdown with Structured Concurrency</title><link href="http://nomisrev.github.io/grateful-shutdown-with-structured-concurrency/" rel="alternate" type="text/html" title="Graceful Shutdown with Structured Concurrency" /><published>2022-11-24T00:00:00+00:00</published><updated>2022-11-24T00:00:00+00:00</updated><id>http://nomisrev.github.io/grateful-shutdown-with-structured-concurrency</id><content type="html" xml:base="http://nomisrev.github.io/grateful-shutdown-with-structured-concurrency/"><![CDATA[<p>In the modern world we often need to make strong guarantees about how our applications terminate; Structured Concurrency gives us a powerful tool to reason about concurrency, parallel processes and how they relate to each other.</p>

<p>This talk will cover some of the issues you might encounter when not respecting graceful shutdown, and how we can leverage Structured Concurrency to reason about these issues.</p>

<p><a href="http://www.youtube.com/watch?v=A69_t_oEP_E" title="Grateful Shutdown with Structured Concurrency"><img src="http://img.youtube.com/vi/A69_t_oEP_E/0.jpg" alt="Graceful Shutdown with Structured Concurrency" /></a></p>]]></content><author><name>Simon Vergauwen</name></author><category term="Kotlin" /><category term="StructuredConcurrency" /><category term="Resource" /><summary type="html"><![CDATA[In the modern world we often need to make strong guarantees about how our applications terminate; Structured Concurrency gives us a powerful tool to reason about concurrency, parallel processes and how they relate to each other.]]></summary></entry><entry><title type="html">Building applications with Kotlin and Arrow.kt in style</title><link href="http://nomisrev.github.io/building-applications-with-kotlin-and-arrow.kt-in-style/" rel="alternate" type="text/html" title="Building applications with Kotlin and Arrow.kt in style" /><published>2022-05-31T00:00:00+00:00</published><updated>2022-05-31T00:00:00+00:00</updated><id>http://nomisrev.github.io/building-applications-with-kotlin-and-arrow.kt-in-style</id><content type="html" xml:base="http://nomisrev.github.io/building-applications-with-kotlin-and-arrow.kt-in-style/"><![CDATA[<p>Webinar with Anton Arhipov on functional microservices with Ktor and Arrow.</p>

<p>The code can be found in the <a href="https://github.com/nomisRev/ktor-arrow-example">Ktor Arrow Example</a> repository.</p>

<p><a href="http://www.youtube.com/watch?v=g79A6HmbW5M" title="Building applications with Kotlin and Arrow.kt in style"><img src="http://img.youtube.com/vi/g79A6HmbW5M/0.jpg" alt="Building applications with Kotlin and Arrow.kt in style" /></a></p>

<p>In this session, we are going to build an end-to-end example that uses the patterns we have discussed in the previous session <a href="https://www.youtube.com/watch?v=IDMmmrRhUvQ">Functional programming in Kotlin with Arrow.kt</a> about functional programming with Kotlin and Arrow.kt.</p>

<p>This time, we will look at the complete workflow from beginning to end, from handling the request, interacting with the database, and sending a response. All in a functional style, of course.</p>]]></content><author><name>Simon Vergauwen</name></author><category term="Kotlin" /><category term="Ktor" /><category term="Either" /><category term="Effect" /><category term="Suspend" /><category term="Continuation" /><summary type="html"><![CDATA[Webinar with Anton Arhipov on functional microservices with Ktor and Arrow.]]></summary></entry><entry><title type="html">Exploring Kotlin’s Context Receivers</title><link href="http://nomisrev.github.io/context-receivers/" rel="alternate" type="text/html" title="Exploring Kotlin’s Context Receivers" /><published>2022-02-17T00:00:00+00:00</published><updated>2022-02-17T00:00:00+00:00</updated><id>http://nomisrev.github.io/context-receivers</id><content type="html" xml:base="http://nomisrev.github.io/context-receivers/"><![CDATA[<p>Last week a long awaited feature was released as a preview in Kotlin 1.6.20-M1.
In this blogpost we’re going to explore what <em>Context Receivers</em> are, and some benefits and patterns they’ll enable.
To try it out in your IDE, follow this <a href="https://kotlinlang.org/docs/install-eap-plugin.html">guide</a></p>

<p>Currently, the only <em>receiver</em> we can define in Kotlin is through <a href="https://kotlinlang.org/docs/extensions.html">extension functions</a>.
In the following function, <code class="language-plaintext highlighter-rouge">fun List&lt;Int&gt;.sum(): Int</code>, we call <code class="language-plaintext highlighter-rouge">List&lt;Int&gt;</code> the <em>receiver</em> of the function.</p>

<p>We can call the above function as a member function on the type <code class="language-plaintext highlighter-rouge">List&lt;Int&gt;</code>.
Note that for a custom defined extension function it requires an import, but not for most functions from the Kotlin Std.</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">listOf</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">).</span><span class="nf">sum</span><span class="p">()</span>
</code></pre></div></div>

<h2 id="what-are-context-receivers">What are Context Receivers</h2>

<p>With <em>Context Receivers</em> we can introduce <em>additional</em> receivers.
Let’s take another function from the Kotlin Std <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/sorted-with.html"><code class="language-plaintext highlighter-rouge">List&lt;A&gt;.sortedWith(comparator: Comparator&lt;A&gt;): List&lt;A&gt;</code></a> and refactor it to use <em>context receivers</em>.</p>

<p>With context receivers we can redefine this function <em>without</em> the <code class="language-plaintext highlighter-rouge">Comparator&lt;A&gt;</code> argument in the parameter list.
Where we call <code class="language-plaintext highlighter-rouge">Comparator&lt;A&gt;</code> the <em>Context receiver</em>, and <code class="language-plaintext highlighter-rouge">List&lt;A&gt;</code> the <em>Extension Receiver</em></p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">context</span><span class="p">(</span><span class="nc">Comparator</span><span class="p">&lt;</span><span class="nc">A</span><span class="p">&gt;)</span>
<span class="k">fun</span> <span class="p">&lt;</span><span class="nc">A</span><span class="p">&gt;</span> <span class="nf">List</span><span class="p">&lt;</span><span class="nc">A</span><span class="p">&gt;.</span><span class="nf">sort</span><span class="p">():</span> <span class="nc">List</span><span class="p">&lt;</span><span class="nc">A</span><span class="p">&gt;</span> <span class="p">=</span>
  <span class="nf">sortedWith</span><span class="p">(</span><span class="k">this</span><span class="nd">@Comparator</span><span class="p">)</span>
</code></pre></div></div>

<p>We can now call this function <em>only</em> from within the <em>context</em> of <code class="language-plaintext highlighter-rouge">Comparator&lt;A&gt;</code>, so we can use Kotlin’s <a href="https://kotlinlang.org/docs/scope-functions.html">scope functions</a> to bring <code class="language-plaintext highlighter-rouge">Comparator&lt;A&gt;</code> into <em>context</em>.</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">with</span><span class="p">(</span><span class="nc">Comparator</span><span class="p">.</span><span class="n">naturalOrder</span><span class="p">&lt;</span><span class="nc">Int</span><span class="p">&gt;())</span> <span class="p">{</span>
  <span class="nf">listOf</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">1</span><span class="p">).</span><span class="nf">sort</span><span class="p">()</span> <span class="c1">// [1, 3, 5]</span>
<span class="p">}</span>

<span class="nc">Comparator</span><span class="p">.</span><span class="n">naturalOrder</span><span class="p">&lt;</span><span class="nc">Int</span><span class="p">&gt;().</span><span class="nf">run</span> <span class="p">{</span>
  <span class="nf">listOf</span><span class="p">(</span><span class="mi">4</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">1</span><span class="p">).</span><span class="nf">sort</span><span class="p">()</span> <span class="c1">// [1, 2, 4, 6]</span>
<span class="p">}</span>
</code></pre></div></div>

<p>What happens if we mark a function with <code class="language-plaintext highlighter-rouge">context(Comparator&lt;A&gt;)</code>, is that it gets an implicit argument that the compiler automatically fills in for us when we’re in its scope.
If we look at the JVM signature we will see <code class="language-plaintext highlighter-rouge">public &lt;A&gt; List&lt;A&gt; sort(List&lt;A&gt; extension, Comparator&lt;A&gt; comporator)</code>, where <em>both</em> receivers are actually regular arguments on the JVM and Kotlin takes care of passing them around for us.</p>

<h2 id="context-receivers-in-action">Context Receivers in action</h2>

<p>So now that we have an understanding of how <em>Context Receivers</em> work, and what terminology is involved, lets take a look at some cool patterns.</p>

<p>In a previous blogposts we’ve discussed <a href="https://nomisrev.github.io/continuation-monad-in-kotlin/"><code class="language-plaintext highlighter-rouge">Effect</code></a> &amp; <a href="https://nomisrev.github.io/inline-and-suspend/"><code class="language-plaintext highlighter-rouge">inline</code> &amp; <code class="language-plaintext highlighter-rouge">suspend</code></a>.
Currently, in Kotlin with Arrow we’d write a function like this <code class="language-plaintext highlighter-rouge">fun readFile(path: String?): Effect&lt;FileError, Content&gt; = effect { ... }</code>.
We’re forced to have a wrapper in the return type, <code class="language-plaintext highlighter-rouge">Effect&lt;FileError, Content&gt;</code>,  to signal to the type system that the function results in <code class="language-plaintext highlighter-rouge">Content</code> but can fail with <code class="language-plaintext highlighter-rouge">FileError</code>.</p>

<p>With <em>Context Receivers</em> we can write code <em>inside the effect context</em>, so  we can rewrite the function as:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@JvmInline</span> <span class="n">value</span> <span class="kd">class</span> <span class="nc">Content</span><span class="p">(</span><span class="kd">val</span> <span class="py">body</span><span class="p">:</span> <span class="nc">List</span><span class="p">&lt;</span><span class="nc">String</span><span class="p">&gt;)</span>

<span class="k">sealed</span> <span class="kd">interface</span> <span class="nc">FileError</span>
<span class="nd">@JvmInline</span> <span class="n">value</span> <span class="kd">class</span> <span class="nc">SecurityError</span><span class="p">(</span><span class="kd">val</span> <span class="py">msg</span><span class="p">:</span> <span class="nc">String</span><span class="p">?)</span> <span class="p">:</span> <span class="nc">FileError</span>
<span class="nd">@JvmInline</span> <span class="n">value</span> <span class="kd">class</span> <span class="nc">FileNotFound</span><span class="p">(</span><span class="kd">val</span> <span class="py">path</span><span class="p">:</span> <span class="nc">String</span><span class="p">)</span> <span class="p">:</span> <span class="nc">FileError</span>
<span class="kd">object</span> <span class="nc">EmptyPath</span> <span class="p">:</span> <span class="nc">FileError</span> <span class="p">{</span>
  <span class="k">override</span> <span class="k">fun</span> <span class="nf">toString</span><span class="p">()</span> <span class="p">=</span> <span class="s">"EmptyPath"</span>
<span class="p">}</span>

<span class="nf">context</span><span class="p">(</span><span class="nc">EffectScope</span><span class="p">&lt;</span><span class="nc">FileError</span><span class="p">&gt;)</span>
<span class="k">suspend</span> <span class="k">fun</span> <span class="nf">readFile</span><span class="p">(</span><span class="n">path</span><span class="p">:</span> <span class="nc">String</span><span class="p">?):</span> <span class="nc">Content</span> <span class="p">{</span>
  <span class="nc">TODO</span><span class="p">(</span><span class="s">"All functionality from effect { } available here"</span><span class="p">)</span>
<span class="p">}</span>
</code></pre></div></div>

<p>So we can now write functions like we love in Kotlin, <code class="language-plaintext highlighter-rouge">suspend fun</code> with the happy-path in the return type.
There are two ways that we can call this function:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">val</span> <span class="py">res</span><span class="p">:</span> <span class="nc">Effect</span><span class="p">&lt;</span><span class="nc">FileError</span><span class="p">,</span> <span class="nc">Content</span><span class="p">&gt;</span> <span class="p">=</span> <span class="nf">effect</span> <span class="p">{</span>
  <span class="nf">readFile</span><span class="p">(</span><span class="s">""</span><span class="p">)</span>
<span class="p">}</span>

<span class="nf">context</span><span class="p">(</span><span class="nc">EffectScope</span><span class="p">&lt;</span><span class="nc">FileError</span><span class="p">&gt;)</span>
<span class="k">suspend</span> <span class="k">fun</span> <span class="nf">allFiles</span><span class="p">(</span><span class="k">vararg</span> <span class="n">path</span><span class="p">:</span> <span class="nc">String</span><span class="p">):</span> <span class="nc">List</span><span class="p">&lt;</span><span class="nc">Content</span><span class="p">&gt;</span> <span class="p">=</span>
  <span class="n">path</span><span class="p">.</span><span class="nf">map</span> <span class="p">{</span> <span class="nf">readFile</span><span class="p">(</span><span class="n">it</span><span class="p">)</span> <span class="p">}</span>
</code></pre></div></div>

<p>However, we can also introduce new context receivers as we go along in our program, for example logging.</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">fun</span> <span class="nf">interface</span> <span class="nc">Logger</span> <span class="p">{</span>
  <span class="k">suspend</span> <span class="k">fun</span> <span class="nf">info</span><span class="p">(</span><span class="n">msg</span><span class="p">:</span> <span class="nc">String</span><span class="p">):</span> <span class="nc">Unit</span>
  <span class="k">suspend</span> <span class="k">fun</span> <span class="nf">warn</span><span class="p">(</span><span class="n">msg</span><span class="p">:</span> <span class="nc">String</span><span class="p">):</span> <span class="nc">Unit</span>
  <span class="k">suspend</span> <span class="k">fun</span> <span class="nf">error</span><span class="p">(</span><span class="n">msg</span><span class="p">:</span> <span class="nc">String</span><span class="p">):</span> <span class="nc">Unit</span>
<span class="p">}</span>

<span class="nf">context</span><span class="p">(</span><span class="nc">EffectScope</span><span class="p">&lt;</span><span class="nc">FileError</span><span class="p">&gt;,</span> <span class="nc">Logger</span><span class="p">)</span>
<span class="k">suspend</span> <span class="k">fun</span> <span class="nf">allFiles</span><span class="p">(</span><span class="k">vararg</span> <span class="n">path</span><span class="p">:</span> <span class="nc">String</span><span class="p">):</span> <span class="nc">List</span><span class="p">&lt;</span><span class="nc">Content</span><span class="p">&gt;</span> <span class="p">{</span>
  <span class="nf">info</span><span class="p">(</span><span class="s">"Processing files"</span><span class="p">)</span>
  <span class="k">return</span> <span class="n">path</span><span class="p">.</span><span class="nf">map</span> <span class="p">{</span> <span class="nf">readFile</span><span class="p">(</span><span class="n">it</span><span class="p">)</span> <span class="p">}</span>
<span class="p">}</span>

<span class="kd">val</span> <span class="py">res2</span><span class="p">:</span> <span class="nc">Effect</span><span class="p">&lt;</span><span class="nc">FileError</span><span class="p">,</span> <span class="nc">Content</span><span class="p">&gt;</span> <span class="p">=</span> <span class="nf">with</span><span class="p">(</span><span class="nc">Logger</span><span class="p">(</span><span class="o">::</span><span class="n">println</span><span class="p">))</span> <span class="p">{</span>
  <span class="nf">effect</span> <span class="p">{</span>
    <span class="nf">allFiles</span><span class="p">(</span><span class="s">"path1"</span><span class="p">,</span> <span class="s">"path2"</span><span class="p">)</span>
  <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Kotlin <em>Context Receivers</em> enable a popular pattern in FP called “Effect Handlers”, which refers to the technique of constraining functionality to an <code class="language-plaintext highlighter-rouge">interface</code> and enabling its functionality by bringing it into <em>scope</em>.
In the example above the <code class="language-plaintext highlighter-rouge">Logger</code> handler enables the <code class="language-plaintext highlighter-rouge">info</code>, <code class="language-plaintext highlighter-rouge">warn</code> and <code class="language-plaintext highlighter-rouge">error</code> functionality.
We can resolve the _EffectScope<FileError>_ part of our _context_ but  leave the `Logger` handler as _context_.</FileError></p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">context</span><span class="p">(</span><span class="nc">Logger</span><span class="p">)</span>
<span class="k">suspend</span> <span class="k">fun</span> <span class="nf">allFilesOrEmpty</span><span class="p">(</span><span class="k">vararg</span> <span class="n">path</span><span class="p">:</span> <span class="nc">String</span><span class="p">):</span> <span class="nc">List</span><span class="p">&lt;</span><span class="nc">Content</span><span class="p">&gt;</span> <span class="p">=</span>
  <span class="n">effect</span><span class="p">&lt;</span><span class="nc">FileError</span><span class="p">,</span> <span class="nc">List</span><span class="p">&lt;</span><span class="nc">Content</span><span class="p">&gt;&gt;</span> <span class="p">{</span>
    <span class="nf">allFiles</span><span class="p">(*</span><span class="n">path</span><span class="p">)</span>
  <span class="p">}.</span><span class="nf">orElse</span> <span class="p">{</span> <span class="nf">emptyList</span><span class="p">()</span> <span class="p">}</span>
</code></pre></div></div>

<p>Here we were able to make resolve the <code class="language-plaintext highlighter-rouge">EffectScope&lt;FileError&gt;</code> context, by wrapping in <code class="language-plaintext highlighter-rouge">effect</code> and resolving the error by defaulting to an <code class="language-plaintext highlighter-rouge">emptyList</code>.
This makes it very easy to solve errors across certain layers in your application,
in case you’d want to resolve <code class="language-plaintext highlighter-rouge">DbError</code> before consuming them in the <em>service</em> layer.</p>

<p>Let’s look at a quick example of what that might look like:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">data class</span> <span class="nc">User</span><span class="p">(</span><span class="kd">val</span> <span class="py">uuid</span><span class="p">:</span> <span class="nc">UUID</span><span class="p">)</span>
<span class="kd">data class</span> <span class="nc">DbError</span><span class="p">(</span><span class="kd">val</span> <span class="py">error</span><span class="p">:</span> <span class="nc">Throwable</span><span class="p">)</span>

<span class="kd">interface</span> <span class="nc">Users</span> <span class="p">{</span>
  <span class="nf">context</span><span class="p">(</span><span class="nc">EffectScope</span><span class="p">&lt;</span><span class="nc">DbError</span><span class="p">&gt;)</span>
  <span class="k">suspend</span> <span class="k">fun</span> <span class="nf">fetchUser</span><span class="p">(</span><span class="n">uuid</span><span class="p">:</span> <span class="nc">UUID</span><span class="p">):</span> <span class="nc">User</span> <span class="p">=</span> <span class="nc">User</span><span class="p">(</span><span class="n">uuid</span><span class="p">)</span>
  
  <span class="k">companion</span> <span class="k">object</span> <span class="nc">Default</span> <span class="p">:</span> <span class="nc">Users</span>
<span class="p">}</span>

<span class="kd">data class</span> <span class="nc">Profile</span><span class="p">(</span><span class="kd">val</span> <span class="py">uuid</span><span class="p">:</span> <span class="nc">UUID</span><span class="p">)</span>
<span class="kd">data class</span> <span class="nc">NetworkError</span><span class="p">(</span><span class="kd">val</span> <span class="py">error</span><span class="p">:</span> <span class="nc">Throwable</span><span class="p">)</span>

<span class="kd">interface</span> <span class="nc">Profiles</span> <span class="p">{</span>
  <span class="nf">context</span><span class="p">(</span><span class="nc">EffectScope</span><span class="p">&lt;</span><span class="nc">NetworkError</span><span class="p">&gt;)</span>
  <span class="k">suspend</span> <span class="k">fun</span> <span class="nf">fetchProfile</span><span class="p">(</span><span class="n">user</span><span class="p">:</span> <span class="nc">User</span><span class="p">):</span> <span class="nc">Profile</span> <span class="p">=</span> <span class="nc">Profile</span><span class="p">(</span><span class="n">user</span><span class="p">.</span><span class="n">uuid</span><span class="p">)</span>

  <span class="k">companion</span> <span class="k">object</span> <span class="nc">Default</span> <span class="p">:</span> <span class="nc">Profiles</span>
<span class="p">}</span>

<span class="nf">context</span><span class="p">(</span><span class="nc">EffectScope</span><span class="p">&lt;</span><span class="nc">DbError</span><span class="p">&gt;,</span> <span class="nc">EffectScope</span><span class="p">&lt;</span><span class="nc">NetworkError</span><span class="p">&gt;,</span> <span class="nc">Profiles</span><span class="p">,</span> <span class="nc">Users</span><span class="p">)</span>
<span class="k">suspend</span> <span class="k">fun</span> <span class="nf">service</span><span class="p">():</span> <span class="nc">Profile</span> <span class="p">{</span>
  <span class="kd">val</span> <span class="py">user</span> <span class="p">=</span> <span class="nf">fetchUser</span><span class="p">(</span><span class="nc">UUID</span><span class="p">.</span><span class="nf">randomUUID</span><span class="p">())</span>
  <span class="k">return</span> <span class="nf">fetchProfile</span><span class="p">(</span><span class="n">user</span><span class="p">)</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Here we have defined a <code class="language-plaintext highlighter-rouge">service</code> function, that talks to the <code class="language-plaintext highlighter-rouge">Persistence</code> layer, and the <code class="language-plaintext highlighter-rouge">Network</code> layer.
Both layers have their own error hierarchy, and we would like to keep them separate, so we don’t have to create a single error hierarchy for all layers.
This also makes it more explicit from which layers the error came from.</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">suspend</span> <span class="k">fun</span> <span class="nf">program</span><span class="p">():</span> <span class="nc">Profile</span><span class="p">?</span> <span class="p">=</span> <span class="nf">with</span><span class="p">(</span><span class="nc">Profiles</span><span class="p">.</span><span class="nc">Default</span><span class="p">)</span> <span class="p">{</span>
  <span class="nf">with</span><span class="p">(</span><span class="nc">Users</span><span class="p">.</span><span class="nc">Default</span><span class="p">)</span> <span class="p">{</span>
    <span class="n">effect</span><span class="p">&lt;</span><span class="nc">DbError</span><span class="p">,</span> <span class="nc">Profile</span><span class="p">?&gt;</span> <span class="p">{</span>
      <span class="n">effect</span><span class="p">&lt;</span><span class="nc">NetworkError</span><span class="p">,</span> <span class="nc">Profile</span><span class="p">?&gt;</span> <span class="p">{</span>
        <span class="nf">service</span><span class="p">(</span><span class="nc">Persistence</span><span class="p">,</span> <span class="nc">Network</span><span class="p">)</span>
      <span class="p">}.</span><span class="nf">tapLeft</span> <span class="p">{</span> <span class="n">networkError</span> <span class="p">-&gt;</span> <span class="nf">println</span><span class="p">(</span><span class="n">networkError</span><span class="p">)</span> <span class="p">}</span>
        <span class="p">.</span><span class="nf">orNull</span><span class="p">()</span>
    <span class="p">}.</span><span class="nf">tapLeft</span> <span class="p">{</span> <span class="n">dbError</span> <span class="p">-&gt;</span> <span class="nf">println</span><span class="p">(</span><span class="n">dbError</span><span class="p">)</span> <span class="p">}</span>
      <span class="p">.</span><span class="nf">orNull</span><span class="p">()</span>
  <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<h2 id="conclusion">Conclusion</h2>

<p>Context receivers give us an elegant way of constraining functions to which context they can be called from.
It allows for composing <em>context</em> without requiring inheritance, and bringing them into <em>scope</em>/<em>context</em> by using Kotlin’s <a href="https://kotlinlang.org/docs/scope-functions.html">scope functions</a>.</p>

<p>The biggest improvement I’m still hoping for is <code class="language-plaintext highlighter-rouge">with</code> that allows multiple parameters, that would allow us to flatten a lot of code.</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">with</span><span class="p">(</span><span class="nc">Users</span><span class="p">.</span><span class="nc">Default</span><span class="p">,</span> <span class="nc">Profiles</span><span class="p">.</span><span class="nc">Default</span><span class="p">)</span> <span class="p">{</span>
  <span class="c1">// Users &amp; Profiles available here</span>
<span class="p">}</span>
</code></pre></div></div>

<p>After having tried context receivers I cannot wait for them to become stable, and will probably start using them in all my toy projects already and perhaps even in some production code.</p>

<p>Thanks for reading my blog, and thoughts on Kotlin’s context receivers.
Hope you enjoyed it!</p>

<p>A Gradle project with the code from this blogpost can be found on GitHub <a href="https://github.com/nomisRev/context-receivers-blog">here</a>.
If you want to try it out do not forget to set up your IDEA as well, instructions can be found <a href="https://kotlinlang.org/docs/install-eap-plugin.html">here</a>.</p>]]></content><author><name>Simon Vergauwen</name></author><category term="Kotlin" /><category term="Suspend" /><category term="DSL" /><category term="Effect" /><summary type="html"><![CDATA[Last week a long awaited feature was released as a preview in Kotlin 1.6.20-M1. In this blogpost we’re going to explore what Context Receivers are, and some benefits and patterns they’ll enable. To try it out in your IDE, follow this guide]]></summary></entry><entry><title type="html">My favorite Kotlin feature</title><link href="http://nomisrev.github.io/inline-and-suspend/" rel="alternate" type="text/html" title="My favorite Kotlin feature" /><published>2022-01-18T00:00:00+00:00</published><updated>2022-01-18T00:00:00+00:00</updated><id>http://nomisrev.github.io/inline-and-suspend</id><content type="html" xml:base="http://nomisrev.github.io/inline-and-suspend/"><![CDATA[<p>Over the last several years I’ve seen many discussions on Kotlin’s features.
Nullability is always a very high ranked one. I like it, but it’s definitely not my favorite feature.</p>

<p>What I love most about Kotlin are some small features, that make the language very elegant. 
Such as smart-casting (contracts), suspend, receiver/extension functions &amp; delegation.</p>

<p>But at this point in time my favorite feature is the combination of <code class="language-plaintext highlighter-rouge">inline</code> and <code class="language-plaintext highlighter-rouge">suspend</code>.</p>

<h1 id="inline-recap">Inline recap</h1>

<p>The <em>inline</em> feature is a feature everyone in Kotlin is using regularly, knowingly or not.
A function can be marked <em>inline</em> when it has lambdas as parameters, also known as Higher Order Functions.
A Higher Order Function is a function that takes other functions as parameters, or returns a new function. We call <code class="language-plaintext highlighter-rouge">map</code> a HOF since it takes another function <code class="language-plaintext highlighter-rouge">transform</code> as a parameter.</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">inline</span> <span class="k">fun</span> <span class="p">&lt;</span><span class="nc">A</span><span class="p">,</span> <span class="nc">B</span><span class="p">&gt;</span> <span class="nf">Iterable</span><span class="p">&lt;</span><span class="nc">A</span><span class="p">&gt;.</span><span class="nf">map</span><span class="p">(</span><span class="n">transform</span><span class="p">:</span> <span class="p">(</span><span class="nc">A</span><span class="p">)</span> <span class="p">-&gt;</span> <span class="nc">B</span><span class="p">):</span> <span class="nc">List</span><span class="p">&lt;</span><span class="nc">B</span><span class="p">&gt;</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">Iterable.map</code> is probably the best known one.
It maps all elements in a <code class="language-plaintext highlighter-rouge">List</code> of type <code class="language-plaintext highlighter-rouge">A</code> to a <code class="language-plaintext highlighter-rouge">List</code> of type <code class="language-plaintext highlighter-rouge">B</code> using the <code class="language-plaintext highlighter-rouge">transform</code> function <code class="language-plaintext highlighter-rouge">(A) -&gt; B</code>.
When these patterns were first introduced, there was some concern about performance due to <em>for-loops</em> being more efficient at byte-code level.</p>

<p><em>inline</em> is a Kotlin compiler feature that can completely get rid of that concern. If we look at the function body of <code class="language-plaintext highlighter-rouge">Iterable.map</code> we see a <em>for-loop</em>.</p>

<p>So let’s see what the bytecode of <code class="language-plaintext highlighter-rouge">listOf(1, 2).map(Int::toString)</code> looks like:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">val</span> <span class="py">destination</span> <span class="p">=</span> <span class="nc">ArrayList</span><span class="p">&lt;</span><span class="nc">String</span><span class="p">&gt;()</span>
<span class="k">for</span> <span class="p">(</span><span class="n">item</span> <span class="k">in</span> <span class="nf">listOf</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">))</span> <span class="p">{</span>
  <span class="n">destination</span><span class="p">.</span><span class="nf">add</span><span class="p">(</span><span class="n">item</span><span class="p">.</span><span class="nf">toString</span><span class="p">())</span>
<span class="p">}</span>  
</code></pre></div></div>

<p>It looks the same as if we’d have written the <em>for-loop</em> by hand. Awesome, we can write high-level code without losing any of the benefits of writing low-level code!</p>

<p>However, inlining is not unique to Kotlin. Many other languages also support inlining.</p>

<h1 id="suspend-recap">suspend recap</h1>

<p><code class="language-plaintext highlighter-rouge">suspend</code> in Kotlin is extremely powerful, and it has many interesting use-cases.
Suspension allows us to wrap callbacks, and write imperative code over callbacks.</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">suspend</span> <span class="k">fun</span> <span class="nf">example</span><span class="p">():</span> <span class="nc">Int</span> <span class="p">=</span> <span class="nf">suspendCoroutine</span> <span class="p">{</span> <span class="n">continuation</span> <span class="p">-&gt;</span>
    <span class="nf">callbackCode</span> <span class="p">{</span> <span class="n">int</span><span class="p">,</span> <span class="n">error</span> <span class="p">-&gt;</span>
      <span class="k">if</span><span class="p">(</span><span class="n">error</span> <span class="p">==</span> <span class="k">null</span><span class="p">)</span> <span class="n">continuation</span><span class="p">.</span><span class="nf">resume</span><span class="p">(</span><span class="n">int</span><span class="p">)</span>
      <span class="k">else</span> <span class="n">continuation</span><span class="p">.</span><span class="nf">resumeWithException</span><span class="p">(</span><span class="n">error</span><span class="p">)</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="k">suspend</span> <span class="k">fun</span> <span class="nf">twice</span><span class="p">()</span> <span class="p">=</span> <span class="nf">example</span><span class="p">()</span> <span class="p">+</span> <span class="nf">example</span><span class="p">()</span>
</code></pre></div></div>

<p>In concurrency that means we can work with <code class="language-plaintext highlighter-rouge">JVM Future</code> or <code class="language-plaintext highlighter-rouge">JS Promise</code> without having to write callback based code.
This is very powerful, as we can now write “regular imperative” to describe powerful async workflows,
but it also allows for very interesting use-cases outside of concurrency.
A great example is discussed at length in my previous <a href="https://nomisrev.github.io/continuation-monad-in-kotlin/">blogpost</a>.</p>

<p>The compiler also verifies that suspending code can only be called from other suspending code, so that you can never accidentally call suspending code from places that do not support it.</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">suspend</span> <span class="k">fun</span> <span class="nf">example</span><span class="p">():</span> <span class="nc">Int</span> <span class="p">=</span> <span class="nf">suspendCoroutine</span> <span class="p">{</span> <span class="n">continuation</span> <span class="p">-&gt;</span>
  <span class="nf">callbackCode</span> <span class="p">{</span> <span class="n">int</span><span class="p">,</span> <span class="n">error</span> <span class="p">-&gt;</span>
    <span class="k">if</span><span class="p">(</span><span class="n">error</span> <span class="p">==</span> <span class="k">null</span><span class="p">)</span> <span class="n">continuation</span><span class="p">.</span><span class="nf">resume</span><span class="p">(</span><span class="n">int</span><span class="p">)</span>
    <span class="k">else</span> <span class="n">continuation</span><span class="p">.</span><span class="nf">resumeWithException</span><span class="p">(</span><span class="n">error</span><span class="p">)</span>
  <span class="p">}</span>
<span class="p">}</span>

<span class="k">fun</span> <span class="nf">once</span><span class="p">()</span> <span class="p">=</span> <span class="nf">example</span><span class="p">()</span>
<span class="c1">// Cannot call suspending fun example from non-suspending fun once</span>
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">suspend</code> functionality is also known as <code class="language-plaintext highlighter-rouge">Continuation Passing Style</code>, which means that the compiler can automatically pass <code class="language-plaintext highlighter-rouge">Continuation</code> between function for us.
It does so in an extremely efficient manner, and that allows us to write callback based code in an immediate manner.</p>

<h1 id="suspend--inline">suspend + inline</h1>

<p>Now that we’ve discussed how <code class="language-plaintext highlighter-rouge">suspend</code> and <code class="language-plaintext highlighter-rouge">inline</code> works,
we can take a look at my favourite Kotlin feature which is support between <code class="language-plaintext highlighter-rouge">suspend</code> + <code class="language-plaintext highlighter-rouge">inline</code>!</p>

<p>Let’s start from a non-inline example.</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">fun</span> <span class="p">&lt;</span><span class="nc">A</span><span class="p">,</span> <span class="nc">B</span><span class="p">&gt;</span> <span class="nf">Iterable</span><span class="p">&lt;</span><span class="nc">A</span><span class="p">&gt;.</span><span class="nf">map</span><span class="p">(</span><span class="n">transform</span><span class="p">:</span> <span class="p">(</span><span class="nc">A</span><span class="p">)</span> <span class="p">-&gt;</span> <span class="nc">B</span><span class="p">):</span> <span class="nc">List</span><span class="p">&lt;</span><span class="nc">A</span><span class="p">&gt;</span> <span class="p">=</span> <span class="nc">TODO</span><span class="p">()</span>

<span class="k">suspend</span> <span class="k">fun</span> <span class="nf">fetchUser</span><span class="p">(</span><span class="n">id</span><span class="p">:</span> <span class="nc">Int</span><span class="p">):</span> <span class="nc">Result</span><span class="p">&lt;</span><span class="nc">Int</span><span class="p">&gt;</span> <span class="p">=</span> <span class="nc">Result</span><span class="p">.</span><span class="nf">success</span><span class="p">(</span><span class="n">id</span><span class="p">)</span>

<span class="k">suspend</span> <span class="k">fun</span> <span class="nf">example5</span><span class="p">()</span> <span class="p">=</span> <span class="nf">listOf</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">).</span><span class="nf">map</span> <span class="p">{</span> <span class="nf">fetchUser</span><span class="p">(</span><span class="n">it</span><span class="p">)</span> <span class="p">}</span>
</code></pre></div></div>

<p>This fails to compile with <em>Suspension functions can be called only within coroutine body</em> even though our <code class="language-plaintext highlighter-rouge">example</code> function is marked as suspend.
This is because we’re creating a <code class="language-plaintext highlighter-rouge">non-suspending lambda transform</code> to pass to the <code class="language-plaintext highlighter-rouge">map</code> function,
and from within that <code class="language-plaintext highlighter-rouge">non-suspending lambda</code> we cannot call the <code class="language-plaintext highlighter-rouge">suspend function fetchUser</code>.</p>

<p>But when we mark this function inline it suddenly works.
That’s because it’s not creating a <code class="language-plaintext highlighter-rouge">non-suspending lambda</code> anymore, but instead in our example we now have again our optimised for-loop and the resolve function is being called from within.</p>

<p>Since the compiler knows that the <code class="language-plaintext highlighter-rouge">non-suspending lambda</code> will not exist due to <code class="language-plaintext highlighter-rouge">inline</code>, it allows <code class="language-plaintext highlighter-rouge">suspend</code> to be called from inside.
This is similar to <em>smart-casting</em>, the compiler has certain knowledge about the program that it allows us to do something that is regularly not allowed.</p>

<p>When designing libraries, or higher order functions it’s important to keep inline in mind.
Not only for performance reasons, but also for <code class="language-plaintext highlighter-rouge">suspend</code>.</p>

<p>It’s one of the features of the Kotlin Compiler that is easily overseen, since it works so transparently.</p>

<h1 id="more-examples">More examples</h1>

<p>Let’s see some other interesting examples, and some caveats.</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">fun</span> <span class="nf">process</span><span class="p">(</span><span class="n">i</span><span class="p">:</span> <span class="nc">Int</span><span class="p">):</span> <span class="nc">Either</span><span class="p">&lt;</span><span class="nc">String</span><span class="p">,</span> <span class="nc">Int</span><span class="p">&gt;</span> <span class="p">=</span> <span class="n">i</span><span class="p">.</span><span class="nf">right</span><span class="p">()</span>

<span class="kd">val</span> <span class="py">res</span><span class="p">:</span> <span class="nc">List</span><span class="p">&lt;</span><span class="nc">Either</span><span class="p">&lt;</span><span class="nc">String</span><span class="p">,</span> <span class="nc">Int</span><span class="p">&gt;&gt;</span> <span class="p">=</span> <span class="p">(</span><span class="mi">0</span><span class="o">..</span><span class="mi">9</span><span class="p">).</span><span class="nf">map</span> <span class="p">{</span> <span class="nf">process</span><span class="p">(</span><span class="n">it</span><span class="p">)</span> <span class="p">}</span>
</code></pre></div></div>

<p>In the above example we have a list of 10 items, and want to process every element.
When we use <code class="language-plaintext highlighter-rouge">Iterable.map</code> we get <code class="language-plaintext highlighter-rouge">List&lt;Either&lt;String, Int&gt;&gt;</code>, which is not that interesting.
Actually we’d want <code class="language-plaintext highlighter-rouge">Either&lt;String, List&lt;Int&gt;&gt;</code>, <em>either the first error, or all processed results</em>.</p>

<p>If you’re familiar with Arrow, or the Cont blogpost you’ve seen a DSL where we can use <code class="language-plaintext highlighter-rouge">suspend</code> to work over <code class="language-plaintext highlighter-rouge">Either.Right</code> in a nicer way.
Since we can combine <code class="language-plaintext highlighter-rouge">inline</code> with <code class="language-plaintext highlighter-rouge">suspend</code>, we can extract the value out of <code class="language-plaintext highlighter-rouge">Either</code> inside <code class="language-plaintext highlighter-rouge">Iterable.map</code>.</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">fun</span> <span class="nf">process</span><span class="p">(</span><span class="n">i</span><span class="p">:</span> <span class="nc">Int</span><span class="p">):</span> <span class="nc">Either</span><span class="p">&lt;</span><span class="nc">String</span><span class="p">,</span> <span class="nc">Int</span><span class="p">&gt;</span> <span class="p">=</span> <span class="n">i</span><span class="p">.</span><span class="nf">right</span><span class="p">()</span>

<span class="kd">val</span> <span class="py">res</span><span class="p">:</span> <span class="nc">Either</span><span class="p">&lt;</span><span class="nc">String</span><span class="p">,</span> <span class="nc">List</span><span class="p">&lt;</span><span class="nc">Int</span><span class="p">&gt;&gt;</span> <span class="p">=</span> <span class="n">either</span><span class="p">.</span><span class="n">eager</span><span class="p">&lt;</span><span class="nc">String</span><span class="p">,</span> <span class="nc">Int</span><span class="p">&gt;</span> <span class="p">{</span>
  <span class="p">(</span><span class="mi">0</span><span class="o">..</span><span class="mi">9</span><span class="p">).</span><span class="nf">map</span> <span class="p">{</span> <span class="nf">process</span><span class="p">(</span><span class="n">it</span><span class="p">).</span><span class="nf">bind</span><span class="p">()</span> <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Now we get the result we’re interested in <code class="language-plaintext highlighter-rouge">Either&lt;String, List&lt;Int&gt;&gt;</code>, <em>either the first error, or all processed results</em>.
If you’re familiar with functional programming, you might see that this replaces the <code class="language-plaintext highlighter-rouge">Traverse</code> and <code class="language-plaintext highlighter-rouge">Monad</code> hierarchy.
So when practicing FP in Kotlin, we can forget about a lot of complexity since it’s possible to provide powerful semantic sugar through suspension.
Note: here we use <code class="language-plaintext highlighter-rouge">either.eager</code> which uses <code class="language-plaintext highlighter-rouge">suspend</code> but doesn’t allow any foreign suspending code.</p>

<p>Another interesting example is <code class="language-plaintext highlighter-rouge">Sequence</code> from Kotlin Std,
where <code class="language-plaintext highlighter-rouge">suspend</code> is used to offer a powerful DSL for building lazy sequences.
<code class="language-plaintext highlighter-rouge">sequence</code> offers <code class="language-plaintext highlighter-rouge">suspend fun yield(a: A): Unit</code> which can be used to <code class="language-plaintext highlighter-rouge">emit</code>/<code class="language-plaintext highlighter-rouge">yield</code> a value to the <code class="language-plaintext highlighter-rouge">Sequence</code>.
Below we can use it to implement <code class="language-plaintext highlighter-rouge">flatMap</code> through <code class="language-plaintext highlighter-rouge">suspend</code> and <code class="language-plaintext highlighter-rouge">inline</code>.</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">fun</span> <span class="p">&lt;</span><span class="nc">A</span><span class="p">,</span> <span class="nc">B</span><span class="p">&gt;</span> <span class="nf">Sequence</span><span class="p">&lt;</span><span class="nc">A</span><span class="p">&gt;.</span><span class="nf">flatMap</span><span class="p">(</span><span class="n">transform</span><span class="p">:</span> <span class="p">(</span><span class="nc">A</span><span class="p">)</span> <span class="p">-&gt;</span> <span class="nc">Sequence</span><span class="p">&lt;</span><span class="nc">B</span><span class="p">&gt;):</span> <span class="nc">Sequence</span><span class="p">&lt;</span><span class="nc">B</span><span class="p">&gt;</span> <span class="p">=</span>
  <span class="nf">sequence</span> <span class="p">{</span>
    <span class="nf">forEach</span> <span class="p">{</span> <span class="n">a</span><span class="p">:</span> <span class="nc">A</span> <span class="p">-&gt;</span>
      <span class="nf">f</span><span class="p">(</span><span class="n">a</span><span class="p">).</span><span class="nf">forEach</span> <span class="p">{</span> <span class="n">b</span><span class="p">:</span> <span class="nc">B</span> <span class="p">-&gt;</span> <span class="k">yield</span><span class="p">(</span><span class="n">b</span><span class="p">)</span> <span class="p">}</span>
    <span class="p">}</span>
  <span class="p">}</span>
</code></pre></div></div>

<ol>
  <li>Open a <code class="language-plaintext highlighter-rouge">sequence</code> DSL block</li>
  <li>Loop over all elements in <code class="language-plaintext highlighter-rouge">Sequence&lt;A&gt;</code></li>
  <li><code class="language-plaintext highlighter-rouge">transform</code> <code class="language-plaintext highlighter-rouge">A</code> into <code class="language-plaintext highlighter-rouge">Sequence&lt;B&gt;</code></li>
  <li>Loop over all elements of <code class="language-plaintext highlighter-rouge">Sequence&lt;B&gt;</code> and yield them</li>
</ol>

<p>The reason we can call <code class="language-plaintext highlighter-rouge">yield</code> from the double nested <code class="language-plaintext highlighter-rouge">forEach</code> is because both are marked as <code class="language-plaintext highlighter-rouge">inline</code>, and thus we can call <code class="language-plaintext highlighter-rouge">yield</code> safely from inside.</p>

<h2 id="caveat">Caveat</h2>

<p>This pattern is sadly not foolproof, there are some gotchas in terms of resource-safety and cancellation.</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">coroutineScope</span> <span class="p">{</span>
  <span class="nf">listOf</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
    <span class="p">.</span><span class="nf">map</span> <span class="p">{</span> <span class="nf">async</span> <span class="p">{</span> <span class="o">..</span><span class="p">.</span> <span class="p">}</span> <span class="p">}</span>
    <span class="p">.</span><span class="nf">map</span> <span class="p">{</span> <span class="n">it</span><span class="p">.</span><span class="nf">await</span><span class="p">()</span> <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>This code is not cancellation safe, if a task fails it can never cancel the other tasks <strong>ahead of it in the list</strong>.
Due to awaiting the <code class="language-plaintext highlighter-rouge">Deferred</code> in the order of the list instead of all at the same time.
To await all the <code class="language-plaintext highlighter-rouge">Deferred</code> at the same time you should use <code class="language-plaintext highlighter-rouge">awaitAll</code>.</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">coroutineScope</span> <span class="p">{</span>
  <span class="nf">listOf</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
    <span class="p">.</span><span class="nf">map</span> <span class="p">{</span> <span class="nf">async</span> <span class="p">{</span> <span class="o">..</span><span class="p">.</span> <span class="p">}</span> <span class="p">}</span>
    <span class="p">.</span><span class="nf">awaitAll</span><span class="p">()</span>
<span class="p">}</span>
</code></pre></div></div>

<h1 id="conclusion">Conclusion</h1>

<p>The way these two features work so seamlessly together is in my opinion an underappreciated feature of the Kotlin compiler and one of my favourites.</p>

<p>An upcoming feature in Kotlin, <a href="https://github.com/Kotlin/KEEP/issues/259">Context receivers</a>, is going to make this pattern more powerful. More on that in a next post.</p>

<p>Thanks for reading my blog on my favorite Kotlin feature(s). I hope you enjoyed it, and a Happy New Year!</p>]]></content><author><name>Simon Vergauwen</name></author><category term="Kotlin" /><category term="Continuation" /><category term="Suspend" /><category term="DSL" /><summary type="html"><![CDATA[Over the last several years I’ve seen many discussions on Kotlin’s features. Nullability is always a very high ranked one. I like it, but it’s definitely not my favorite feature.]]></summary></entry><entry><title type="html">Functional programming in Kotlin with Arrow.kt</title><link href="http://nomisrev.github.io/functional-programming-in-kotlin-with-arrow-kt/" rel="alternate" type="text/html" title="Functional programming in Kotlin with Arrow.kt" /><published>2021-12-05T00:00:00+00:00</published><updated>2021-12-05T00:00:00+00:00</updated><id>http://nomisrev.github.io/functional-programming-in-kotlin-with-arrow-kt</id><content type="html" xml:base="http://nomisrev.github.io/functional-programming-in-kotlin-with-arrow-kt/"><![CDATA[<p>Webinar with Anton Arhipov &amp; Alejandro Serrano about functional microservices with Ktor and Arrow.</p>

<p><a href="http://www.youtube.com/watch?v=IDMmmrRhUvQ" title="Functional programming in Kotlin with Arrow.kt"><img src="http://img.youtube.com/vi/IDMmmrRhUvQ/0.jpg" alt="Functional programming in Kotlin with Arrow.kt" /></a></p>

<p>Arrow strives to be a great functional companion library for Kotlin. This is not just a matter of style: with this functional style we can describe complex patterns in an easy way, and we aim to showcase a few of them in the context of a Ktor project. We’ll discuss how to handle retries using circuit breakers and schedulers, and how to do validation in a powerful fashion. Along the way, we’ll show a bit of other Arrow projects, like optics and analysis.</p>]]></content><author><name>Simon Vergauwen</name></author><category term="Kotlin" /><category term="Either" /><category term="Effect" /><category term="Suspend" /><summary type="html"><![CDATA[Webinar with Anton Arhipov &amp; Alejandro Serrano about functional microservices with Ktor and Arrow.]]></summary></entry><entry><title type="html">Continuation&amp;lt;R, A&amp;gt; in Kotlin</title><link href="http://nomisrev.github.io/continuation-monad-in-kotlin/" rel="alternate" type="text/html" title="Continuation&amp;lt;R, A&amp;gt; in Kotlin" /><published>2021-11-28T00:00:00+00:00</published><updated>2021-11-28T00:00:00+00:00</updated><id>http://nomisrev.github.io/continuation-monad-in-kotlin</id><content type="html" xml:base="http://nomisrev.github.io/continuation-monad-in-kotlin/"><![CDATA[<p>Coroutines is one of the most liked features in Kotlin. Most people are familiar with the KotlinX Coroutines implementation,
and many are also familiar with <code class="language-plaintext highlighter-rouge">suspendCoroutine</code> from the Kotlin Standard Library and then have also come across <code class="language-plaintext highlighter-rouge">Continuation</code>.</p>

<p>Kotlin has support for CPS, or Continuation Passing Style,
which means that the compiler has a <em>style</em> in which it can automatically <em>pass</em> <em>Continuation</em> between functions that are marked with <code class="language-plaintext highlighter-rouge">suspend</code>.</p>

<p>This means that in every <code class="language-plaintext highlighter-rouge">suspend fun</code> we have access to an implicit <code class="language-plaintext highlighter-rouge">Continuation</code> parameter through <code class="language-plaintext highlighter-rouge">suspendCoroutine { effect: Continuation -&gt; ... }</code>, or any of it’s lower level variants.</p>

<p>This <code class="language-plaintext highlighter-rouge">Continuation</code> only has a single type parameter <code class="language-plaintext highlighter-rouge">Continuation&lt;A&gt;</code>, and the <em>result</em> of running this <code class="language-plaintext highlighter-rouge">suspend</code>/<code class="language-plaintext highlighter-rouge">Continuation</code> based program is <em>either</em> <code class="language-plaintext highlighter-rouge">A</code>, or <code class="language-plaintext highlighter-rouge">Throwable</code>.
This is represented by the <code class="language-plaintext highlighter-rouge">Result&lt;A&gt;</code> type from the Kotlin Standard Library.</p>

<p>In functional programming we often prefer to interrupt the program with a typed value <code class="language-plaintext highlighter-rouge">R</code> instead of <code class="language-plaintext highlighter-rouge">Throwable</code>. 
So we’d like a <code class="language-plaintext highlighter-rouge">Continuation</code> that instead of only being able to result in <code class="language-plaintext highlighter-rouge">A | Throwable</code> can result in <code class="language-plaintext highlighter-rouge">A | R | Throwable</code>,
you can never escape that a program can also result in <code class="language-plaintext highlighter-rouge">Throwable</code> and <code class="language-plaintext highlighter-rouge">suspend</code> explicitly takes <code class="language-plaintext highlighter-rouge">Throwable</code> into account to operate correctly.</p>

<p>To achieve this we define a new type <code class="language-plaintext highlighter-rouge">interface Effect&lt;R, A&gt;</code>, 
which represents a function of <code class="language-plaintext highlighter-rouge">suspend () -&gt; A</code> that can fail with <code class="language-plaintext highlighter-rouge">R</code> (and <code class="language-plaintext highlighter-rouge">Throwable</code>).
It’s defined by <code class="language-plaintext highlighter-rouge">suspend fun &lt;B&gt; fold(f: suspend (R) -&gt; B, g: suspend (A) -&gt; B): B</code>.</p>

<p>What is interesting about the <code class="language-plaintext highlighter-rouge">Effect&lt;R, A&gt;</code> type is it’s a suspend function <code class="language-plaintext highlighter-rouge">fold</code>, so it doesn’t rely on any wrappers such as <code class="language-plaintext highlighter-rouge">Either</code>, <code class="language-plaintext highlighter-rouge">Ior</code> or <code class="language-plaintext highlighter-rouge">Validated</code>.
Only when <code class="language-plaintext highlighter-rouge">fold</code> is called it will create a <code class="language-plaintext highlighter-rouge">Continuation</code> and run the computation, this means <code class="language-plaintext highlighter-rouge">Effect</code> can encode <code class="language-plaintext highlighter-rouge">side-effects</code> as <code class="language-plaintext highlighter-rouge">pure values</code>.
This makes <code class="language-plaintext highlighter-rouge">Effect&lt;R, A&gt;</code> a very efficient generic runtime.</p>

<p>To construct a <code class="language-plaintext highlighter-rouge">Effect&lt;R, A&gt;</code> we simply call the <code class="language-plaintext highlighter-rouge">effect&lt;R, A&gt; { }</code> constructor, which exposes a rich syntax through the lambda receiver <code class="language-plaintext highlighter-rouge">suspend EffectScope&lt;R&gt;.() -&gt; A</code>.</p>

<h2 id="working-with-effectr-a">Working with Effect&lt;R, A&gt;</h2>

<p>Let’s write a small program to read a file from disk, and instead of having the program work exception based we want to turn it into a polymorphic type-safe program.</p>

<p>We start by defining a small function that accepts a <code class="language-plaintext highlighter-rouge">String</code>, and does some simply validation to check that the path is not empty.
If the path is empty, we want to program to result in <code class="language-plaintext highlighter-rouge">EmptyPath</code>.
So we’re immediately going to see how we can raise an error of any arbitrary type <code class="language-plaintext highlighter-rouge">R</code> by using the function <code class="language-plaintext highlighter-rouge">shift</code>. 
The name <code class="language-plaintext highlighter-rouge">shift</code> comes shifting (or changing, especially unexpectedly), away from the computation and finishing the <code class="language-plaintext highlighter-rouge">Continuation</code> with <code class="language-plaintext highlighter-rouge">R</code>.</p>

<!--- TEST_NAME ContSpec -->
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">object</span> <span class="nc">EmptyPath</span>

<span class="k">fun</span> <span class="nf">readFile</span><span class="p">(</span><span class="n">path</span><span class="p">:</span> <span class="nc">String</span><span class="p">):</span> <span class="nc">Effect</span><span class="p">&lt;</span><span class="nc">EmptyPath</span><span class="p">,</span> <span class="nc">Unit</span><span class="p">&gt;</span> <span class="p">=</span> <span class="nf">effect</span> <span class="p">{</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">path</span><span class="p">.</span><span class="nf">isEmpty</span><span class="p">())</span> <span class="nf">shift</span><span class="p">(</span><span class="nc">EmptyPath</span><span class="p">)</span> <span class="k">else</span> <span class="nc">Unit</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Here we see how we can define a <code class="language-plaintext highlighter-rouge">Effect&lt;R, A&gt;</code> which has <code class="language-plaintext highlighter-rouge">EmptyPath</code> for the shifted type <code class="language-plaintext highlighter-rouge">R</code>, and <code class="language-plaintext highlighter-rouge">Unit</code> for the success type <code class="language-plaintext highlighter-rouge">A</code>.</p>

<p>Patterns like validating a <code class="language-plaintext highlighter-rouge">Boolean</code> is very common, and the <code class="language-plaintext highlighter-rouge">Effect</code> DSL offers utility functions like <code class="language-plaintext highlighter-rouge">kotlin.require</code> and <code class="language-plaintext highlighter-rouge">kotlin.requireNotNull</code>. They’re named <code class="language-plaintext highlighter-rouge">ensure</code> and <code class="language-plaintext highlighter-rouge">ensureNotNull</code> to avoid conflicts with the <code class="language-plaintext highlighter-rouge">kotlin</code> namespace. So let’s rewrite the function from above to use the DSL instead.</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">fun</span> <span class="nf">readFile2</span><span class="p">(</span><span class="n">path</span><span class="p">:</span> <span class="nc">String</span><span class="p">?):</span> <span class="nc">Effect</span><span class="p">&lt;</span><span class="nc">EmptyPath</span><span class="p">,</span> <span class="nc">Unit</span><span class="p">&gt;</span> <span class="p">=</span> <span class="nf">effect</span> <span class="p">{</span>
  <span class="nf">ensureNotNull</span><span class="p">(</span><span class="n">path</span><span class="p">)</span> <span class="p">{</span> <span class="nc">EmptyPath</span> <span class="p">}</span>
  <span class="nf">ensure</span><span class="p">(</span><span class="n">path</span><span class="p">.</span><span class="nf">isNotEmpty</span><span class="p">())</span> <span class="p">{</span> <span class="nc">EmptyPath</span> <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<blockquote>
  <p>You can get the full code <a href="https://github.com/nomisRev/nomisrev.github.io/blob/master/guide/example/example-readme-01.kt">here</a>.</p>
</blockquote>

<p>Now that we have the path, we can read from the <code class="language-plaintext highlighter-rouge">File</code> and return it as a domain model <code class="language-plaintext highlighter-rouge">Content</code>.
We also want to take a look at what exceptions reading from a file might occur <code class="language-plaintext highlighter-rouge">FileNotFoundException</code> &amp; <code class="language-plaintext highlighter-rouge">SecurityError</code>, so lets make some domain errors for those too. Grouping them as a sealed interface is useful since that way we can resolve <em>all</em> errors in a type safe manner.</p>

<!--- INCLUDE
import java.io.*
-->
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@JvmInline</span>
<span class="n">value</span> <span class="kd">class</span> <span class="nc">Content</span><span class="p">(</span><span class="kd">val</span> <span class="py">body</span><span class="p">:</span> <span class="nc">List</span><span class="p">&lt;</span><span class="nc">String</span><span class="p">&gt;)</span>

<span class="k">sealed</span> <span class="kd">interface</span> <span class="nc">FileError</span>
<span class="nd">@JvmInline</span> <span class="n">value</span> <span class="kd">class</span> <span class="nc">SecurityError</span><span class="p">(</span><span class="kd">val</span> <span class="py">msg</span><span class="p">:</span> <span class="nc">String</span><span class="p">?)</span> <span class="p">:</span> <span class="nc">FileError</span>
<span class="nd">@JvmInline</span> <span class="n">value</span> <span class="kd">class</span> <span class="nc">FileNotFound</span><span class="p">(</span><span class="kd">val</span> <span class="py">path</span><span class="p">:</span> <span class="nc">String</span><span class="p">)</span> <span class="p">:</span> <span class="nc">FileError</span>
<span class="kd">object</span> <span class="nc">EmptyPath</span> <span class="p">:</span> <span class="nc">FileError</span> <span class="p">{</span>
  <span class="k">override</span> <span class="k">fun</span> <span class="nf">toString</span><span class="p">()</span> <span class="p">=</span> <span class="s">"EmptyPath"</span>
<span class="p">}</span>
</code></pre></div></div>

<p>We can finish our function, but we need to refactor our return value from <code class="language-plaintext highlighter-rouge">Unit</code> to <code class="language-plaintext highlighter-rouge">Content</code> and our error type from <code class="language-plaintext highlighter-rouge">EmptyPath</code> to <code class="language-plaintext highlighter-rouge">FileError</code>.</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">fun</span> <span class="nf">readFile</span><span class="p">(</span><span class="n">path</span><span class="p">:</span> <span class="nc">String</span><span class="p">?):</span> <span class="nc">Effect</span><span class="p">&lt;</span><span class="nc">FileError</span><span class="p">,</span> <span class="nc">Content</span><span class="p">&gt;</span> <span class="p">=</span> <span class="nf">effect</span> <span class="p">{</span>
  <span class="nf">ensureNotNull</span><span class="p">(</span><span class="n">path</span><span class="p">)</span> <span class="p">{</span> <span class="nc">EmptyPath</span> <span class="p">}</span>
  <span class="nf">ensure</span><span class="p">(</span><span class="n">path</span><span class="p">.</span><span class="nf">isNotEmpty</span><span class="p">())</span> <span class="p">{</span> <span class="nc">EmptyPath</span> <span class="p">}</span>
  <span class="k">try</span> <span class="p">{</span>
    <span class="kd">val</span> <span class="py">lines</span> <span class="p">=</span> <span class="nc">File</span><span class="p">(</span><span class="n">path</span><span class="p">).</span><span class="nf">readLines</span><span class="p">()</span>
    <span class="nc">Content</span><span class="p">(</span><span class="n">lines</span><span class="p">)</span>
  <span class="p">}</span> <span class="k">catch</span> <span class="p">(</span><span class="n">e</span><span class="p">:</span> <span class="nc">FileNotFoundException</span><span class="p">)</span> <span class="p">{</span>
    <span class="nf">shift</span><span class="p">(</span><span class="nc">FileNotFound</span><span class="p">(</span><span class="n">path</span><span class="p">))</span>
  <span class="p">}</span> <span class="k">catch</span> <span class="p">(</span><span class="n">e</span><span class="p">:</span> <span class="nc">SecurityException</span><span class="p">)</span> <span class="p">{</span>
    <span class="nf">shift</span><span class="p">(</span><span class="nc">SecurityError</span><span class="p">(</span><span class="n">e</span><span class="p">.</span><span class="n">message</span><span class="p">))</span>
  <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">Effect</code> returned by <code class="language-plaintext highlighter-rouge">readFile</code> function represents a <code class="language-plaintext highlighter-rouge">suspend fun</code> that will return:</p>
<ul>
  <li>the <code class="language-plaintext highlighter-rouge">Content</code> of a given <code class="language-plaintext highlighter-rouge">path</code></li>
  <li>a <code class="language-plaintext highlighter-rouge">FileError</code></li>
  <li>An unexpected fatal <code class="language-plaintext highlighter-rouge">Throwable</code> (<code class="language-plaintext highlighter-rouge">OutOfMemoryException</code>)</li>
</ul>

<p>The returned <code class="language-plaintext highlighter-rouge">Effect&lt;FileError, Content&gt;</code> can executed into a value.</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">suspend</span> <span class="k">fun</span> <span class="nf">test</span><span class="p">()</span> <span class="p">{</span>
  <span class="nf">readFile</span><span class="p">(</span><span class="s">""</span><span class="p">).</span><span class="nf">toEither</span><span class="p">()</span> <span class="n">shouldBe</span> <span class="nc">Either</span><span class="p">.</span><span class="nc">Left</span><span class="p">(</span><span class="nc">EmptyPath</span><span class="p">)</span>
  <span class="nf">readFile</span><span class="p">(</span><span class="s">"knit.properties"</span><span class="p">).</span><span class="nf">toValidated</span><span class="p">()</span> <span class="n">shouldBe</span>  <span class="nc">Validated</span><span class="p">.</span><span class="nc">Invalid</span><span class="p">(</span><span class="nc">FileNotFound</span><span class="p">(</span><span class="s">"knit.properties"</span><span class="p">))</span>
  <span class="nf">readFile</span><span class="p">(</span><span class="s">"gradle.properties"</span><span class="p">).</span><span class="nf">toIor</span><span class="p">()</span> <span class="n">shouldBe</span> <span class="nc">Ior</span><span class="p">.</span><span class="nc">Left</span><span class="p">(</span><span class="nc">FileNotFound</span><span class="p">(</span><span class="s">"gradle.properties"</span><span class="p">))</span>
  <span class="nf">readFile</span><span class="p">(</span><span class="s">"README.MD"</span><span class="p">).</span><span class="nf">toOption</span> <span class="p">{</span> <span class="nc">None</span> <span class="p">}</span> <span class="n">shouldBe</span> <span class="nc">None</span>

  <span class="nf">readFile</span><span class="p">(</span><span class="s">"build.gradle.kts"</span><span class="p">)</span>
    <span class="p">.</span><span class="nf">fold</span><span class="p">({</span> <span class="n">_</span><span class="p">:</span> <span class="nc">FileError</span> <span class="p">-&gt;</span> <span class="k">null</span> <span class="p">},</span> <span class="p">{</span> <span class="n">it</span> <span class="p">})</span>
    <span class="p">.</span><span class="n">shouldBeInstanceOf</span><span class="p">&lt;</span><span class="nc">Content</span><span class="p">&gt;()</span>
    <span class="p">.</span><span class="n">body</span><span class="p">.</span><span class="nf">shouldNotBeEmpty</span><span class="p">()</span>
<span class="p">}</span>
</code></pre></div></div>
<blockquote>
  <p>You can get the full code <a href="https://github.com/nomisRev/nomisrev.github.io/blob/master/guide/example/example-readme-02.kt">here</a>.
<!--- TEST lines.isEmpty() --></p>
</blockquote>

<h2 id="handling-errors">Handling errors</h2>

<p>Handling errors of type <code class="language-plaintext highlighter-rouge">R</code> is the same as handling errors for any other data type in Arrow.
<code class="language-plaintext highlighter-rouge">Effect&lt;R, A&gt;</code> offers <code class="language-plaintext highlighter-rouge">handleError</code>, <code class="language-plaintext highlighter-rouge">handleErrorWith</code>, <code class="language-plaintext highlighter-rouge">redeem</code>, <code class="language-plaintext highlighter-rouge">redeemWith</code> and <code class="language-plaintext highlighter-rouge">attempt</code>.</p>

<p>As you can see in the examples below it is possible to resolve errors of <code class="language-plaintext highlighter-rouge">R</code> or <code class="language-plaintext highlighter-rouge">Throwable</code> in <code class="language-plaintext highlighter-rouge">Effect&lt;R, A&gt;</code>.</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">val</span> <span class="py">failed</span><span class="p">:</span> <span class="nc">Effect</span><span class="p">&lt;</span><span class="nc">String</span><span class="p">,</span> <span class="nc">Int</span><span class="p">&gt;</span> <span class="p">=</span>
  <span class="nf">effect</span> <span class="p">{</span> <span class="nf">shift</span><span class="p">(</span><span class="s">"failed"</span><span class="p">)</span> <span class="p">}</span>

<span class="kd">val</span> <span class="py">resolved</span><span class="p">:</span> <span class="nc">Effect</span><span class="p">&lt;</span><span class="nc">Nothing</span><span class="p">,</span> <span class="nc">Int</span><span class="p">&gt;</span> <span class="p">=</span>
  <span class="n">failed</span><span class="p">.</span><span class="nf">handleError</span> <span class="p">{</span> <span class="n">it</span><span class="p">.</span><span class="n">length</span> <span class="p">}</span>

<span class="kd">val</span> <span class="py">newError</span><span class="p">:</span> <span class="nc">Effect</span><span class="p">&lt;</span><span class="nc">List</span><span class="p">&lt;</span><span class="nc">Char</span><span class="p">&gt;,</span> <span class="nc">Int</span><span class="p">&gt;</span> <span class="p">=</span>
  <span class="n">failed</span><span class="p">.</span><span class="nf">handleErrorWith</span> <span class="p">{</span> <span class="n">str</span> <span class="p">-&gt;</span>
    <span class="nf">effect</span> <span class="p">{</span> <span class="nf">shift</span><span class="p">(</span><span class="n">str</span><span class="p">.</span><span class="nf">reversed</span><span class="p">().</span><span class="nf">toList</span><span class="p">())</span> <span class="p">}</span>
  <span class="p">}</span>

<span class="kd">val</span> <span class="py">redeemed</span><span class="p">:</span> <span class="nc">Effect</span><span class="p">&lt;</span><span class="nc">Nothing</span><span class="p">,</span> <span class="nc">Int</span><span class="p">&gt;</span> <span class="p">=</span>
  <span class="n">failed</span><span class="p">.</span><span class="nf">redeem</span><span class="p">({</span> <span class="n">str</span> <span class="p">-&gt;</span> <span class="n">str</span><span class="p">.</span><span class="n">length</span> <span class="p">},</span> <span class="o">::</span><span class="n">identity</span><span class="p">)</span>

<span class="kd">val</span> <span class="py">captured</span><span class="p">:</span> <span class="nc">Effect</span><span class="p">&lt;</span><span class="nc">String</span><span class="p">,</span> <span class="nc">Result</span><span class="p">&lt;</span><span class="nc">Int</span><span class="p">&gt;&gt;</span> <span class="p">=</span> <span class="n">effect</span><span class="p">&lt;</span><span class="nc">String</span><span class="p">,</span> <span class="nc">Int</span><span class="p">&gt;</span> <span class="p">{</span>
  <span class="mi">1</span>
<span class="p">}.</span><span class="nf">attempt</span><span class="p">()</span>

<span class="k">suspend</span> <span class="k">fun</span> <span class="nf">test</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">failed</span><span class="p">.</span><span class="nf">toEither</span><span class="p">()</span> <span class="n">shouldBe</span> <span class="nc">Either</span><span class="p">.</span><span class="nc">Left</span><span class="p">(</span><span class="s">"failed"</span><span class="p">)</span>
  <span class="n">resolved</span><span class="p">.</span><span class="nf">toEither</span><span class="p">()</span> <span class="n">shouldBe</span> <span class="nc">Either</span><span class="p">.</span><span class="nc">Right</span><span class="p">(</span><span class="mi">6</span><span class="p">)</span>
  <span class="n">newError</span><span class="p">.</span><span class="nf">toEither</span><span class="p">()</span> <span class="n">shouldBe</span> <span class="nc">Either</span><span class="p">.</span><span class="nc">Left</span><span class="p">(</span><span class="nf">listOf</span><span class="p">(</span><span class="sc">'d'</span><span class="p">,</span> <span class="sc">'e'</span><span class="p">,</span> <span class="sc">'l'</span><span class="p">,</span> <span class="sc">'i'</span><span class="p">,</span> <span class="sc">'a'</span><span class="p">,</span> <span class="sc">'f'</span><span class="p">))</span>
  <span class="n">redeemed</span><span class="p">.</span><span class="nf">toEither</span><span class="p">()</span> <span class="n">shouldBe</span> <span class="nc">Either</span><span class="p">.</span><span class="nc">Right</span><span class="p">(</span><span class="mi">6</span><span class="p">)</span>
  <span class="n">captured</span><span class="p">.</span><span class="nf">toEither</span><span class="p">()</span> <span class="n">shouldBe</span> <span class="nc">Either</span><span class="p">.</span><span class="nc">Right</span><span class="p">(</span><span class="nc">Result</span><span class="p">.</span><span class="nf">success</span><span class="p">(</span><span class="mi">1</span><span class="p">))</span>
<span class="p">}</span>
</code></pre></div></div>
<blockquote>
  <p>You can get the full code <a href="https://github.com/nomisRev/nomisrev.github.io/blob/master/guide/example/example-readme-03.kt">here</a>.
<!--- TEST lines.isEmpty() --></p>
</blockquote>

<h2 id="effecte-a-and-eithere-a">Effect&lt;E, A&gt; and Either&lt;E, A&gt;</h2>

<p>We’ve briefly mentioned the difference between <code class="language-plaintext highlighter-rouge">Either&lt;E, A&gt;</code> and <code class="language-plaintext highlighter-rouge">Effect&lt;E, A&gt;</code> but let’s compare them in some more detail.</p>

<p><code class="language-plaintext highlighter-rouge">Either&lt;String, Int&gt;</code> represents a <em>value</em> of <em>either</em> a <code class="language-plaintext highlighter-rouge">String</code> or an <code class="language-plaintext highlighter-rouge">Int</code>,
while <code class="language-plaintext highlighter-rouge">Effect&lt;String, Int&gt;</code> represents a <em>function</em> that will result in an <code class="language-plaintext highlighter-rouge">Int</code>, interrupt with a <code class="language-plaintext highlighter-rouge">String</code>, or throw a <code class="language-plaintext highlighter-rouge">Throwable</code>.</p>

<p>So <code class="language-plaintext highlighter-rouge">Effect&lt;String, Int&gt;</code> can represent a <em>function</em> that results in <em>either</em> a <code class="language-plaintext highlighter-rouge">String</code>, an <code class="language-plaintext highlighter-rouge">Int</code> or throw a <code class="language-plaintext highlighter-rouge">Throwable</code>.
That is exactly what the <code class="language-plaintext highlighter-rouge">either</code> DSL of Arrow Core does, and let’s see what the implementation might look like with <code class="language-plaintext highlighter-rouge">Effect</code>.</p>

<p>Since <code class="language-plaintext highlighter-rouge">Effect&lt;E, A&gt;</code> can interrupt with a <code class="language-plaintext highlighter-rouge">String</code> we can implement <code class="language-plaintext highlighter-rouge">bind</code> for <code class="language-plaintext highlighter-rouge">Either&lt;String, Int&gt;</code>.
Here we implement <code class="language-plaintext highlighter-rouge">bind</code> how it’s implemented in the library, it’s defined in <code class="language-plaintext highlighter-rouge">EffectScope&lt;E&gt;</code> which is the DSL available inside <code class="language-plaintext highlighter-rouge">effect { }</code>.</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">interface</span> <span class="nc">EffectScope</span><span class="p">&lt;</span><span class="nc">E</span><span class="p">&gt;</span> <span class="p">{</span>
  <span class="k">suspend</span> <span class="k">fun</span> <span class="p">&lt;</span><span class="nc">A</span><span class="p">&gt;</span> <span class="nf">shift</span><span class="p">(</span><span class="n">e</span><span class="p">:</span> <span class="n">e</span><span class="p">):</span> <span class="nc">A</span>
  
  <span class="k">suspend</span> <span class="k">fun</span> <span class="p">&lt;</span><span class="nc">A</span><span class="p">&gt;</span> <span class="nf">Either</span><span class="p">&lt;</span><span class="nc">E</span><span class="p">,</span> <span class="nc">A</span><span class="p">&gt;.</span><span class="nf">bind</span><span class="p">():</span> <span class="nc">A</span> <span class="p">=</span>
    <span class="k">when</span><span class="p">(</span><span class="k">this</span><span class="p">)</span> <span class="p">{</span>
      <span class="k">is</span> <span class="nc">Either</span><span class="p">.</span><span class="nc">Right</span> <span class="p">-&gt;</span> <span class="n">value</span>
      <span class="k">is</span> <span class="nc">Either</span><span class="p">.</span><span class="nc">Left</span> <span class="p">-&gt;</span> <span class="nf">shift</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>When we encounter <code class="language-plaintext highlighter-rouge">Either.Right</code> we can simply return the value, and when we encounter <code class="language-plaintext highlighter-rouge">Either.Left</code> we short-circuit (interrupt) the function.
This allows us to use the <code class="language-plaintext highlighter-rouge">effect { }</code> DSL similarly to how we use <code class="language-plaintext highlighter-rouge">either { }</code> from Arrow Core.</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">suspend</span> <span class="k">fun</span> <span class="nf">test</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">effect</span><span class="p">&lt;</span><span class="nc">String</span><span class="p">,</span> <span class="nc">Int</span><span class="p">&gt;</span> <span class="p">{</span>
    <span class="kd">val</span> <span class="py">x</span><span class="p">:</span> <span class="nc">Int</span> <span class="p">=</span> <span class="mi">1</span><span class="p">.</span><span class="nf">right</span><span class="p">().</span><span class="nf">bind</span><span class="p">()</span>
    <span class="kd">val</span> <span class="py">y</span><span class="p">:</span> <span class="nc">Int</span> <span class="p">=</span> <span class="nf">shift</span><span class="p">(</span><span class="s">"Failed"</span><span class="p">)</span>
  <span class="p">}.</span><span class="nf">toEither</span><span class="p">()</span> <span class="n">shouldBe</span> <span class="nc">Either</span><span class="p">.</span><span class="nc">Left</span><span class="p">(</span><span class="s">"failed"</span><span class="p">)</span>
<span class="p">}</span>
</code></pre></div></div>
<blockquote>
  <p>You can get the full code <a href="https://github.com/nomisRev/nomisrev.github.io/blob/master/guide/example/example-readme-04.kt">here</a>.
<!--- TEST lines.isEmpty() --></p>
</blockquote>

<p>At the end of our DSL we call <code class="language-plaintext highlighter-rouge">toEither</code> to finally turn the <code class="language-plaintext highlighter-rouge">Effect</code> result into <code class="language-plaintext highlighter-rouge">Either</code>.
So we can re-define the <code class="language-plaintext highlighter-rouge">either</code> DSL from Arrow with following function:</p>

<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">suspend</span> <span class="k">fun</span> <span class="p">&lt;</span><span class="nc">E</span><span class="p">,</span> <span class="nc">A</span><span class="p">&gt;</span> <span class="nf">either</span><span class="p">(</span><span class="n">block</span><span class="p">:</span> <span class="k">suspend</span> <span class="nc">EffectScope</span><span class="p">&lt;</span><span class="nc">E</span><span class="p">&gt;.()</span> <span class="p">-&gt;</span> <span class="nc">A</span><span class="p">):</span> <span class="nc">Either</span><span class="p">&lt;</span><span class="nc">E</span><span class="p">,</span> <span class="nc">A</span><span class="p">&gt;</span> <span class="p">=</span> <span class="nf">effect</span><span class="p">(</span><span class="n">block</span><span class="p">).</span><span class="nf">toEither</span><span class="p">()</span>
</code></pre></div></div>

<p>So we can consider <code class="language-plaintext highlighter-rouge">Effect</code> a higher abstraction to write programs that can result in <code class="language-plaintext highlighter-rouge">Either</code>, <code class="language-plaintext highlighter-rouge">Validated</code>, <code class="language-plaintext highlighter-rouge">Option</code>, <code class="language-plaintext highlighter-rouge">Ior</code>, <code class="language-plaintext highlighter-rouge">Result</code>, etc</p>

<h2 id="structured-concurrency">Structured Concurrency</h2>

<p><code class="language-plaintext highlighter-rouge">Effect&lt;R, A&gt;</code> can automatically operate with KotlinX’s Structured Concurrency by leveraging <code class="language-plaintext highlighter-rouge">kotlin.cancellation.CancellationException</code> introduced in Kotlin 1.4.
It’s used by <code class="language-plaintext highlighter-rouge">shift</code> to raise error values of type <code class="language-plaintext highlighter-rouge">R</code> inside the <code class="language-plaintext highlighter-rouge">Continuation</code> since it effectively cancels/short-circuits it.
For this reason <code class="language-plaintext highlighter-rouge">shift</code> adheres to the same rules as <a href="https://kotlinlang.org/docs/coroutines-basics.html#structured-concurrency"><code class="language-plaintext highlighter-rouge">Structured Concurrency</code></a></p>

<p>For more details see the <a href="https://github.com/nomisRev/Continuation#structured-concurrency"><code class="language-plaintext highlighter-rouge">Effect&lt;R, A&gt;</code> documentation</a></p>

<h2 id="conclusion">Conclusion</h2>

<p>The <code class="language-plaintext highlighter-rouge">Effect</code> type will soon become available in Arrow!
There is also <code class="language-plaintext highlighter-rouge">RestrictedCont</code> which exposes the same functionality without requiring <code class="language-plaintext highlighter-rouge">suspend</code>.</p>

<p>Thank you for reading the first informal (test) blog on my Github Pages, I hope you enjoyed it!
Feel free to reach out on KotlinLang Slack for feedback or questions.</p>

<p>Stay tuned for more informal blogs!</p>]]></content><author><name>Simon Vergauwen</name></author><category term="Kotlin" /><category term="Continuation" /><category term="Monad" /><category term="Either" /><category term="Effect" /><summary type="html"><![CDATA[Coroutines is one of the most liked features in Kotlin. Most people are familiar with the KotlinX Coroutines implementation, and many are also familiar with suspendCoroutine from the Kotlin Standard Library and then have also come across Continuation.]]></summary></entry></feed>