<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Beatrice Kinya on Medium]]></title>
        <description><![CDATA[Stories by Beatrice Kinya on Medium]]></description>
        <link>https://medium.com/@kinya?source=rss-90181ab7429f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jZ4o-d1F8MIvOedFVMfZeQ.jpeg</url>
            <title>Stories by Beatrice Kinya on Medium</title>
            <link>https://medium.com/@kinya?source=rss-90181ab7429f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 08:10:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kinya/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[#TIL: Statement vs Expressions]]></title>
            <link>https://kinya.medium.com/til-statement-vs-expressions-108d20f48588?source=rss-90181ab7429f------2</link>
            <guid isPermaLink="false">https://medium.com/p/108d20f48588</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[imperative-programming]]></category>
            <category><![CDATA[program-language-design]]></category>
            <category><![CDATA[idiomatic-expressions]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Beatrice Kinya]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 06:01:01 GMT</pubDate>
            <atom:updated>2026-06-09T06:01:01.222Z</atom:updated>
            <content:encoded><![CDATA[<h4>What is a = b = c = 4 ?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tBCZoS0z7DViZ9aeJ88pZA.jpeg" /><figcaption>Herringbone pattern #crochet</figcaption></figure><p>a, b, and c are variables. In your favourite programming language, what will be the output of the following code?</p><pre>a = b = c = 4<br>print(a)<br><br>A) Undefined<br>B) 4<br>C) Runtime Exception<br>D) Syntax error</pre><p>Intuitively, you might lean toward <strong>B</strong>. But, it depends on the grammar — the syntax — of the language.</p><p>S<strong>tatements </strong>and <strong>expressions </strong>are core building blocks of most programming languages<strong>. </strong>Let’s delve into what they are and see how they solve our puzzle.</p><h4>Statement</h4><p>A statement represents an action to be carried out or a side effect to be executed. It is an instruction to the computer to do something, but it doesn’t return a value.</p><p>Examples <em>using Kotlin</em>:</p><ul><li>Variable declaration:</li></ul><pre>val num = 10</pre><ul><li>Class declaration:</li></ul><pre>class User (val name: String)</pre><ul><li>Loops (for, while):</li></ul><pre>for ( i in 0..5 ) {<br>  println(i)<br>}</pre><h4>Expression</h4><p>An expression is a piece of code that produces a value.</p><p>For example, <em>using Kotlin</em>:</p><ul><li>3 + 4 produces 7</li><li>maxOf(1, 3) produces 3</li><li>if (a &lt; b) a else b produces the value of a if it is less than the value of b. Otherwise it produces the value of b .</li><li>num &gt; 100 produces true or false</li></ul><p>3 + 4 , maxOf(1, 3) and num &gt; 100 are expressions.</p><p>Since expressions always evaluate to a value, you can build complex logic by combining several smaller expressions, just like <strong>Lego blocks.</strong></p><p>Example using Kotlin collections:</p><pre>val activePremiumUserEmails = users<br>    .filter { it.isActive }            // 1st expression<br>    .filter { it.hasPremiumAccess() }  // 2nd expression<br>    .map { it.email.lowercase() }      // 3rd expression</pre><p>Instead of executing separate, standalone instructions, these expressions pass values down the pipeline:</p><ul><li>The <strong>1st expression </strong>evaluates and returns a list of active users.</li><li>The <strong>2nd expression </strong>takes the list of active users handed down from the previous step, filters it further and returns active users with premium access.</li><li>The <strong>3rd expression</strong> receives the premium users list, grabs each user’s email and converts it to lowercase.</li></ul><p>In the end, this chain of expressions transforms a list of User objects to a list of String objects, the emails.</p><blockquote>…There are evil and unfriendly things in the world that have little love for those who go on two legs … Aragon, ‘The fellowship of Rings’.</blockquote><p>⚠️ <strong>When composing expressions, be wary of the readability of code. Just because you can compose the expressions, it doesn’t mean you should.</strong></p><p>Bad example:</p><pre>val totalPayment = 500.0 + <br>    (when {<br>        creditScore &gt; 750 -&gt; -25.0<br>        creditScore &lt; 600 -&gt; 50.0<br>        else -&gt; 0.0<br>    }) + <br>    (if (isPaymentLate) 35.0 else 0.0)</pre><p>While this code uses the when and if expressions correctly, it forces the reader to do mental math to figure out how the totalPayment is calculated.</p><p>To write idiomatic expressions, follow this simple rule: <strong>keep nesting shallow, and use the type system to stack the steps sequentially, </strong>t<em>hanks to the Kotlin extension functions.</em></p><p>This allows the other developer to read code from left to right, top to bottom, like a sequence.</p><p>First, we isolate the business logic into extension functions:</p><pre>fun Double.applyCreditScore(score: Int): Double = this + when {<br>        score &gt; 750 -&gt; -25.0<br>        score &lt; 600 -&gt; 50.0<br>        else -&gt; 0.0<br>    }<br><br><br>fun Double.applyLateFee(isPaymentLate: Boolean): Double = <br>    this + if (isPaymentLate) 35.0 else 0.0</pre><p>Now we can compose totalPayment calculation like this:</p><pre>val basepay = 500.0<br><br>val totalPayment = basepay<br>     .applyCreditScore(creditScore)<br>     .applyLateFee(isPaymentLate)</pre><h4>So what’s the answer?</h4><p>In Kotlin, a = b = c = 4 will produce a<strong> syntax error</strong>, because an assignment in Kotlin is a statement and does not produce a value.</p><p>In languages like C and Java, however, the output is <strong>4</strong> because an assignment is an expression. Since assignment is right-associative, the code will be evaluated from right to left like this:</p><pre>a = b = c = 4<br>a = (b = (c = 4)) // c is assigned 4, and the expression returns 4<br>a = (b = 4)       // b is assigned 4, and the expression returns 4<br>a = 4.            // a is assigned 4</pre><p><em>“It comes in pints? I’m getting one!”</em> — <em>Pippin</em></p><p>Thanks for sticking around. To more idiomatic code! 🥂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=108d20f48588" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integer, The Floating Type and Everything]]></title>
            <link>https://kinya.medium.com/integer-the-floating-type-and-everything-3e112a3c8a8c?source=rss-90181ab7429f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e112a3c8a8c</guid>
            <category><![CDATA[integer]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Beatrice Kinya]]></dc:creator>
            <pubDate>Sun, 26 Apr 2026 19:56:36 GMT</pubDate>
            <atom:updated>2026-04-26T20:57:00.690Z</atom:updated>
            <content:encoded><![CDATA[<h4>Type, Integer, Float</h4><p>Remember the grade 7 Mathematics?</p><pre>17 / 30 = 0.56666666666</pre><p>When you put this in your favourite programming language, thanks to types, the result is zero</p><pre>val result = 17/ 30<br>println(result)<br>// Output: 0</pre><p>In statically typed languages like C, C++, Java, Kotlin, if both numbers are integers, the computer performs an <em>integer division, </em>and the<em> </em>result is truncated towards zero, i.e ignores the decimal and keeps the whole number closest to zero.</p><p>To get a decimal value, you have to tell the compiler to treat the numbers as floating-point values by making at least one number a <em>double</em>.</p><pre>val result = 17.0 /30<br>println(result)<br>// Output: 0.5666666666666667</pre><h4>The Modern Twist</h4><p>In modern languages like Python and JavaScript, the computer assumes you want the most accurate answer possible. Hence, dividing two integers the result is a floating-point value.</p><pre>result = 17 / 30<br># result will be 0.5666666666666667</pre><p>If you want the result to be truncated, you have to use the floor division operator ( <em>// )</em>.</p><pre>result = 17 // 30<br># result will be 0</pre><p>Any interstellar traveller knows that the details matter. Just remember, the answer to Life, the Universe and Everything might be 42 — but only if you’ve used the right data types.</p><p>Don’t Panic! 🤓</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e112a3c8a8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Composing App State, or there and back again]]></title>
            <link>https://kinya.medium.com/composing-app-state-or-there-and-back-again-8526e01c3f8f?source=rss-90181ab7429f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8526e01c3f8f</guid>
            <category><![CDATA[finite-state-machine]]></category>
            <category><![CDATA[state-machine]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[state-management]]></category>
            <dc:creator><![CDATA[Beatrice Kinya]]></dc:creator>
            <pubDate>Fri, 29 Aug 2025 11:46:09 GMT</pubDate>
            <atom:updated>2025-09-25T18:05:38.498Z</atom:updated>
            <content:encoded><![CDATA[<h4>Kotlin, Square Workflow</h4><p>I first learned about using state machines as a presenter pattern from <a href="https://speakerdeck.com/rygelouv/state-machines-and-how-they-shape-mobile-architectures">“State Machines and How they Shape Mobile Architectures</a>” talk by <a href="https://medium.com/u/6e59272c2fb9">Rygel Louv</a> at <a href="https://droidcon.co.ke/">Droidcon KE</a>. I was fascinated.</p><p>A finite state machine is an abstract machine that can be in exactly one of a finite number of <strong><em>states</em></strong> at any given time. The FSM can change from one state to another in response to some inputs; the change from one state to another is called a <strong><em>transition</em></strong><em>(</em><a href="https://en.wikipedia.org/wiki/Finite-state_machine"><em>Wikipedia</em></a><em>). F</em>or example, a light bulb.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*bi2Uu2ZwJZnuI7pBRcOIqw.png" /></figure><p>I was on the hunt for how others were implementing the pattern, then I came across <a href="https://github.com/square/workflow-kotlin/tree/main">Square’s Workflow framework</a>, which implements a composable state machine model. Let’s dive into how it works.</p><h3>What is a Workflow?</h3><p>A Workflow is at the heart of the framework.</p><p>From the <a href="https://square.github.io/workflow/glossary/#workflow-instance">Square Workflow glossary</a>: “ A Workflow (Instance)is an object that defines the transitions and side effects of a state machine.”</p><p>So, what does that actually look like in practice?</p><p>A Workflow is an interface with three type parameters, PropsT , OutputT , and RenderingT :</p><pre>public interface Workflow&lt;PropsT, OutputT, out RenderingT&gt;{…}</pre><p>There are two implementations of the Workflow interface: StatefulWorkflow and StatelessWorkflow .</p><p>A StatefulWorkflow has an additional type parameter, StateT . This is the internal state of the Workflow</p><pre>public abstract class StatefulWorkflow&lt;PropsT, StateT, OutputT, out RenderingT&gt;</pre><p>A Workflow takes input as Props . If a Workflow does not have any input, Props can beUnit . Then the Workflow returns a Rendering .</p><p>A Rendering is a view model or a screen. A view model is an object that holds the values and event handlers needed to create a user interface, i.e., what to show. It only contains information needed for the view to work. It isn’t tied to any specific UI platform.</p><p>For example, the SearchWorkflow</p><pre>object SearchResultWorkflow :<br>    StatelessWorkflow&lt;SearchResultProps, BackPressed, SearchResultScreen&gt;() {<br><br>    data class SearchResultProps(<br>        val query: String,<br>        val searchBy: String,<br>        val result: SearchResult<br>    )<br><br>    override fun render(<br>        renderProps: SearchResultProps,<br>        context: RenderContext<br>    ): SearchResultScreen = SearchResultScreen(<br>        query = renderProps.query,<br>        result = renderProps.result,<br>        onBackPressed = { }<br>    )<br>}</pre><p>The rendering, SearchScreen , looks like this</p><pre>data class SearchResultScreen(<br>    val query: String,<br>    val result: SearchResult,<br>    val onBackPressed: () -&gt; Unit = {}<br>) : ComposeScreen { ... }</pre><blockquote>See the complete code 👉🏽 : <a href="https://github.com/BKinya/Bookflow">Bookflow</a></blockquote><h3>Managing State</h3><p>A StatefulWorkflow maintains its internal state. The state is immutable. A WorkflowAction defines the state transitions.</p><p>When an external event, like a user tapping the search button, aWorkflowAction is enqueued to be processed by the workflow runtime. Let’s briefly examine the key parts of the WorkflowAction:</p><pre>public abstract class WorkflowAction&lt;PropsT, StateT, OutputT&gt; {<br>    <br>    ...<br>    public inner class Updater(<br>        public val props: PropsT,<br>        public var state: StateT<br>    ) {<br>        internal val startingState = state<br>        ...<br>    }<br><br>    public abstract fun Updater.apply()<br>}</pre><p>The inner classUpdater has a mutable property state . This property is used to update the state of a Workflow.</p><p>Updater.apply() is the function you implement to update the state of a Workflow. Besides updating the state, theapply() function can also set the Output to emit from a workflow or execute side effects.</p><p>To create a WorkflowAction , you’d implement the WorkflowAction like this:</p><pre>private fun onSearch(searchBy: String, query: String) = <br>    object : WorkflowAction&lt;Unit, State, Nothing&gt;() {<br>        override fun Updater.apply() {<br>            this.state = LoadingSearchResult(searchBy, query)<br>        }<br>        override val debuggingName: String<br>            get() = &quot;onSearch&quot;<br>    }</pre><p>The apply() function provides the context to read and change the state of the Workflow. This is the only place you’re allowed to update the state.</p><p>The framework provides action factory function you’d use to create the WorkflowAction concisely:</p><pre>private fun onSearch(searchBy: String, query: String) = action(&quot;onSearch&quot;) { <br>    state = LoadingSearchResult(searchBy = searchBy, query = query)<br>}</pre><p>When the apply function returns the updated object containing the new state, workflow runtime replaces the old state with the new state, triggering render() function of a Workflow to update the view model.</p><p>A Workflow receives input as Propsand returns a view model. When an event is received from the outside world, a WorkflowAction is dispatched to be handled by the Workflow runtime. The apply() method is called to update the state. Once the state has been updated, the workflow runtime calls the render() function of the Workflow to update the view model. With this unidirectional data flow, the state of your app is centralised, state changes are predictable and easy to reason about.</p><h3>Composing state machines</h3><p>Each Workflow is a small, independent state machine.</p><blockquote>From the <a href="https://square.github.io/workflow/glossary/#workflow-node">glossary</a>: “A Workflow(Node) is an active state machine whose behavior is defined by a Workflow Instance. This is the object that is held by the Workflow Runtime and whose state is updated (or “driven”) according to the behavior declared in the Workflow Instance. In Kotlin and Swift a Workflow Node is implemented with the private WorkflowNode class/struct.”</blockquote><p>A parent workflow can render one or more child workflows using context.renderChild(childWorkflow) function.</p><p>The parent workflow can send Props to the child. Then the child workflow produces Rendering of its own and can emit Output to its parents. The parent workflow then maps the Output to an action it can handle.</p><pre>context.renderChild(<br>    child = SearchResultWorkflow,<br>    props = SearchResultProps(<br>        query = renderState.searchQuery,<br>        searchBy = renderState.searchBy,<br>        result = renderState.result<br>    )<br>) { output -&gt;<br>    // Handle output<br>    onBackNavigation()<br>}<br><br>private fun onBackNavigation() = action(&quot;backNavigation&quot;) {<br>    state = ShowSearchScreen()<br>}</pre><p>This enables you to create scalable features by creating small, modular workflows that handle specific tasks and then nesting them within the larger parent workflows.</p><h3>Conclusion</h3><p>With Square’s workflow library, you can build complex and scalable features as <strong>composable state machines. </strong>The state in the app is predictable, easy to reason about, and easy to test, too. The modularity simplifies your code.</p><p>To get started, check out this <a href="https://github.com/square/workflow-kotlin/tree/main/samples/tutorial">tutorial</a></p><h4>Resources</h4><ul><li><a href="https://github.com/square/workflow-kotlin">https://github.com/square/workflow-kotlin</a></li><li><a href="https://github.com/BKinya/Bookflow">https://github.com/BKinya/Bookflow</a></li></ul><p><em>Adios! Hasta luego!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8526e01c3f8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#UnchartedTerritory. What if I moved to a new city?]]></title>
            <link>https://kinya.medium.com/unchartedterritory-what-if-i-moved-to-a-new-city-5f1a1321145b?source=rss-90181ab7429f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f1a1321145b</guid>
            <category><![CDATA[relocation]]></category>
            <category><![CDATA[glovo]]></category>
            <category><![CDATA[barcelona]]></category>
            <dc:creator><![CDATA[Beatrice Kinya]]></dc:creator>
            <pubDate>Sun, 23 Mar 2025 17:43:15 GMT</pubDate>
            <atom:updated>2025-03-23T17:43:15.844Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KKBkjLy53EpGWTRi0KATAw.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@apasaric/">Aleksandar Pasaric</a></figcaption></figure><p>I’ve always had this idea in the back of my mind: one day, I’ll move to a new country and work there. Eventually, it happened a little sooner than I thought. Next, I was doing interviews for an Android Engineer at Glovo, battling visa applications. Then, Bam! Barcelona.</p><p>On arrival, I had ..two weeks. Two weeks! To find an apartment to rent. Almost immediately, I started sending messages to real estate agents hoping to schedule apartment viewing. If you talked to anyone I met that first week, they’d tell you all about how stressed I was about house hunting. It was, like, my main topic of any conversation.</p><p>Towards the end of week one, I started doubting my strategy. I had contacted a million and one house agents, pun intended, and was talking to friends and acquaintances. I was running out of time.</p><p>Aha! How about consulting a relocation agent? All over again, I started sending messages to various relocation agents, some of whom have never replied since. Eventually, I found a great relocation consultant and started working with <a href="https://www.google.com/maps/place/Barcelona+Es+Mi+Casa+-+Servicios+Inmobiliarios+Para+Expatriados/@41.6826904,1.8514293,8.07z/data=!4m16!1m9!3m8!1s0x2bd8379be141d4ef:0x3e8100dee22f9af1!2sBarcelona+Es+Mi+Casa+-+Servicios+Inmobiliarios+Para+Expatriados!8m2!3d41.7578529!4d2.0689905!9m1!1b1!16s%2Fg%2F11wbyd15y_!3m5!1s0x2bd8379be141d4ef:0x3e8100dee22f9af1!8m2!3d41.7578529!4d2.0689905!16s%2Fg%2F11wbyd15y_?entry=ttu&amp;g_ep=EgoyMDI1MDMxOS4yIKXMDSoASAFQAw%3D%3D">Natalia, Barcelona Es Mi Casa</a> to help me find an apartment. In 4 weeks since the start of the process, we had secured an apartment. One and a half months since I arrived in Barcelona.</p><blockquote>This is not a sponsored post, but Natalia is a great agent. She will assist you in getting your desired home and conduct a through research to ensure that apartment owners follow all the legal regulations. This is huge for me as I was really afraid of being scammed. I’d highly recommend Natalia.</blockquote><p>Now that I finally found an apartment everything feels a little more lively. Ready to figure out what the city has in store for me.</p><p>First things first, the language.</p><p><em>¿Hola, Cómo estás?</em></p><p>I started learning Spanish a little before traveling but every time I hear people speaking the language, it feels like a whole new language. The subtle nuances in pronunciation, and the sheer volume of unfamiliar words.</p><p>Even simple phrases I thought I knew vanish from my memory, replaced by a blank stare and a desperate, “Lo siento, no entiendo.” I can read a book, the short stories, I can drill the vocabulary, but real-world Spanish? It’s a different beast entirely.</p><p>Nonetheless, it’s been a great experience so far. I’ve met kind and friendly people. I’m learning to rhythm of this new city and, of course, the language. I can’t wait to see what lies ahead.</p><p>¡Adios! Hasta Luego</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f1a1321145b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Structured Concurrency: coroutineScope]]></title>
            <link>https://kinya.medium.com/structrured-concurrency-coroutinescope-adc470d47e4b?source=rss-90181ab7429f------2</link>
            <guid isPermaLink="false">https://medium.com/p/adc470d47e4b</guid>
            <category><![CDATA[coroutinescope]]></category>
            <category><![CDATA[structured-concurrency]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Beatrice Kinya]]></dc:creator>
            <pubDate>Sat, 05 Oct 2024 14:57:49 GMT</pubDate>
            <atom:updated>2026-04-16T19:33:33.674Z</atom:updated>
            <content:encoded><![CDATA[<h4>Kotlin, Coroutine, Concurrency</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pvex1FxffbWYzpxAVDe2GQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@leoearthancha">Lingyun Hou</a> on <a href="https://unsplash.com/">unsplash</a></figcaption></figure><p>Structured concurrency ensures proper management and coordination of concurrent tasks <em>within a well-defined scope</em><strong>. </strong>When using Kotlin coroutines, structured concurrency is enforced by the <em>coroutine scopes</em><strong>. </strong>Check out <a href="https://elizarov.medium.com/structured-concurrency-722d765aa952">this article</a> to learn more about structured concurrency with Kotlin coroutines.</p><blockquote>Coroutines are always related to some local <em>scope</em> in your application, which is an entity with a limited lifetime, like a UI element. So, with structured concurrency, we now <em>require</em> that launch is invoked in aCoroutineScope, which is an interface implemented by your lifetime-limited objects, like UI elements or a viewmodel</blockquote><blockquote><a href="https://elizarov.medium.com/structured-concurrency-722d765aa952">Structured Concurrency by Roman Elizarov</a></blockquote><p>Coroutine builders like launch and async are extension functions on the CoroutineScope interface.</p><pre>public fun CoroutineScope.launch(<br> context: CoroutineContext = EmptyCoroutineContext,<br> start: CoroutineStart = CoroutineStart.DEFAULT,<br> block: suspend CoroutineScope.() -&gt; Unit<br>): Job {<br> ...<br>}</pre><p>Here is how you’d launch coroutines whose life time is bound to the life time of the MainActivity class.</p><pre>class MainActivity : ComponentActivity() {<br><br>    /**<br>     * MainScope() create a coroutine scope tied to<br>     * Android main thread. It uses Dispatchers.Main<br>     * and has a SupervisorJob.<br>     */<br>    private val mainScope = MainScope()<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        ...<br>    }<br><br>    fun drawSomething(){<br>        mainScope.launch {<br>            // draw in the main thread<br>            draw()<br>        }<br>    }<br><br>    override fun onDestroy() {<br>        super.onDestroy()<br>        /**<br>         * Cancel all coroutines launched in this scope once the<br>         * activity is destroyed.<br>         */<br>        mainScope.cancel()<br>    }<br>}</pre><p>When the instance of the activity class is destroyed, cancelling the mainScope cancels all the coroutines started in the scope.</p><p>This is fine and dandy. However, some times you’d like to executed multiple tasks concurrently. Consider the following code:</p><pre>// A long running operation<br>suspend fun generateValue(): Int{<br>    delay(3000)<br>    return Random.nextInt(0, 10)<br>}<br><br>suspend fun computeSum(): Int{<br>    val num1 = generateValue()<br>    println(&quot;Num 1 =&gt; $num1&quot;)<br>    val num2 = generateValue()<br>    println(&quot;Num 2 =&gt; $num2&quot;)<br>    return num1 + num2<br>}<br><br>// prints<br>// Num 1 =&gt; 3<br>// Num 2 =&gt; 2</pre><p>In the computeSum() function, computing num2 waits until num1 completes execution. Hence, generating num1blocks generating num2. This’ a bummer! Isn’t the whole point of using coroutines to avoid blocking threads?</p><p>I suspect you’ve already figured out how to solve this issue. Have you? Read on to find out.</p><p>Before discussing the solution, let’s first learn about the coroutineScope function.</p><h4>coroutineScope</h4><p>coroutineScope is a suspending function that creates a new coroutine scope and calls the specified coroutine within this scope. This function waits for the completion of its children before it completes itself and returns. When any child coroutine in this scope fails, the scope fails too, canceling all other children.</p><p>Using the coroutineScope function, you’d start two concurrent tasks to generate the numbers. Since the coroutineScopefunction can return a value, you’ll return the sum of two numbers from the block to the computeSum() function which the returns the sum value to its caller.</p><pre>suspend fun computeSum(): Int {<br>    val sum = coroutineScope {<br>        // Coroutine #1<br>        val num1 = async {<br>            println(&quot;Generating num#1&quot;)<br>            val value = generateValue()<br>            println(&quot;num#1 done =&gt; $value&quot;)<br>            value<br>        }<br>        // Coroutine #2<br>        val num2 = async {<br>            println(&quot;Generating num#2&quot;)<br>            val value = generateValue()<br>            println(&quot;num#2 done =&gt; $value&quot;)<br>            value<br>        }<br>        num1.await() + num2.await()<br>    }<br>    return sum<br>}<br>// prints<br>// Generating num#1<br>// Generating num#2<br>// num#1 =&gt; 2<br>// num#2 =&gt; 3</pre><p>The above code starts two coroutines by calling async twice. <em>Coroutine#1 </em>starts executing printing <em>Generating num#1. </em>When the delay() function in the generateValue() function is called, it triggers the suspension of <em>Coroutine#1</em>. This frees up the main thread for <em>#Coroutine#2 </em>to start work.</p><p>async function returns a deferred object, Deffered&lt;T&gt;. await() suspends execution of a coroutine until the deferred object completes and returns its result. After suspending for 3 secs <em>Coroutine#1 </em>continues its work returning the generated value followed by <em>Coroutine#2.</em></p><p>Yay! With this implementation, none of the operations will block the thread. And you preserved the desired structured concurrency. All the async coroutines are children of the scope created by the coroutineScope function. The children will be canceled when the scope is canceled.</p><p><strong><em>A challenge: </em></strong>You’d like to get a list of items from an API service<em>. </em>There is no single endpoint to get all the items together. Each item has a unique endpoint. Could you use multiple parallel tasks to fetch the items concurrently?</p><p><strong>NB: </strong>Fetching the tasks sequentially will block the thread.</p><p><strong><em>Solution:</em></strong></p><pre>/**<br> * Get all episodes where a character is featured<br> */<br>fun getCharacterEpisodes(episodeUrls: List&lt;String&gt;): Flow&lt;List&lt;String&gt;&gt; = flow{<br>    coroutineScope {<br>        val episodes = episodeUrls.map { url -&gt;<br>            // 1<br>            async { getOneEpisode(url) }<br>        }<br>        // 2<br>        emit(episodes.awaitAll())<br>    }<br>}</pre><ol><li>Using async you’re creating a coroutine to execute the long-running tasks to fetch each item. There will be as many coroutines as there are items in the list running concurrently.</li><li>awaitAll() suspends execution of a coroutine until all deferred objects in a collection are complete. It’d fail as soon as any of it deferred fails.</li></ol><p>Happy Coding! Or There and Back again 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adc470d47e4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tail Recursion]]></title>
            <link>https://kinya.medium.com/tail-recursion-306f0a1170f4?source=rss-90181ab7429f------2</link>
            <guid isPermaLink="false">https://medium.com/p/306f0a1170f4</guid>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[tail-recursion]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Beatrice Kinya]]></dc:creator>
            <pubDate>Mon, 05 Aug 2024 15:57:06 GMT</pubDate>
            <atom:updated>2024-08-05T18:17:32.592Z</atom:updated>
            <content:encoded><![CDATA[<h4>Kotlin</h4><blockquote>Function programming — where algebra meets code.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nRZZxyXA53KsAw7rx849_w.jpeg" /><figcaption>Photo Taken Author</figcaption></figure><p>The previous article, <a href="https://kinya.medium.com/the-art-of-recursion-1d41a6160b5c#3624">the art of recursion</a>, showed that deep levels of recursion can cause stack overflow errors. However, all is not lost. Kotlin allows your recursive algorithms in a <strong>tail-recursive </strong>style and no longer risk your app crashing from stack overflow errors.</p><p>A tail-recursive function is a function <em>whose the last action is a call to itself</em>. When the compiler detects a tail recursive function, it will transform the function into a loop like version. Consequently, the function will require only one stack frame — eliminating the need for additional stack frames.</p><p>This sum function from <a href="https://kinya.medium.com/the-art-of-recursion-1d41a6160b5c">the previous article</a>, is it tail-recursive?</p><pre>fun sum(nums: List&lt;Int&gt;): Int =<br>    if (nums.isEmpty()) {<br>        0<br>    } else {<br>        nums[0] + sum(nums.drop(1))<br>    }</pre><p>It could tempting to think it is. But it’s not.</p><p>When the else block is evaluated, the compiler will find this:</p><pre>nums[0] + sum(nums.drop(1))</pre><p>There are three operations:</p><ul><li>Get the first integer in the list, nums[0] .</li><li>Call to the sum function with the remaining integers in the list.</li><li>Add the value returned by the sum function to the first integer in the list.</li></ul><p>If you express this in code:</p><pre>val y = nums[0]<br>val x = sum(nums.drop(1))<br>val res = x + y<br>return result</pre><p>How could you make the sum function tail recursive?</p><p>Kotlin provides a tailrec modifier. If you mark a function with the tailrec modifier and it meets the requirements of a tail recursion, the compiler will optimise the function to a loop like version.</p><p>If you try to label the sum function with the tailrec modifier, the IDE will complain because the sum function does not meet the requirements of a tail recursion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*i7uuBDQVQDlq7IIxqHXvxQ.png" /></figure><p>You can make the sum function tail recursive using the following simple steps.</p><ol><li>Keep the original function signature the same. The sum function signature does not change.</li><li>Create the second function, call it sumWithAccumulator and make it private. This new function will have the same signature as the original one and with an additional parameter, accumulator: Int . Then mark the function with the tailrec modifier. It’s signature will look like this:</li></ol><pre>private tailrec fun sumWithAccumulator(<br>    nums: List&lt;Int&gt;,<br>    accumulator: Int<br>): Int = ???</pre><p>3. Copy the implementation of the original function to this new function. Then modify it to use the accumulator parameter:</p><pre>private tailrec fun sumWithAccumulator(<br>    nums: List&lt;Int&gt;,<br>    accumulator: Int<br>): Int =<br>    if (nums.isEmpty()) {<br>        accumulator<br>    } else {<br>        sumWithAccumulator(nums.drop(1), accumulator + nums[1])<br>    }</pre><p>A few things things to note:</p><p>I marked the function with the tailrec modifier to tell the complier to optimise it. There are no IDE warnings since the function meets the requirements of a tail recursion.</p><p><strong>Warning: </strong>If you mark a function that does not meet the requirements of a tail recursion with the tailrec modifier, the compiler will not optimise the function and there are possibilities of a stack overflow errors.</p><p>The first parameter of the function is the list of integers. The function has the second parameter, the accumulator . When the base case is reached, the function returns the accumulator instead of 0 .</p><p>The original sum function passed to itself the remaining integers and added the result <em>later</em> the first integer in the list. This new approach keeps track of the “accumulator” (total sum) with each recursive call. As a result, the last action of thesumWithAccumulator function is a call to itself. Like this:</p><pre>sumWithAccumulator(nums.drop(1), accumulator + nums[1])</pre><p>Now, the compiler can optimise the function into a loop like version. And you still have the benefits of functional code. How cool!</p><p>4. For the last step, you’ll call sumWithAccumulator function from the sum function passing the list of integers and an identity value as the initial value of theaccumulator . The identity value for sum algorithm is 0. The identity value for product algorthm is 1. The identity value for string concatenation is an empty string.(“”).</p><pre>fun sum(nums: List&lt;Int&gt;): Int = sumWithAccumulator(nums, 0)</pre><p>When you maintain the original sum function signature, the other programmers using the function will not have to provide the initial seed value. They’ll will not even know that the algorithm used a seed. (Maybe they shouldn’t know🤪).</p><h4>Bonus</h4><p>A tail recursive function to calculate the factorial of an integer:</p><pre>fun factorial(num: Int): Int = factorialWithAccumulator(num, accumulator = 1)<br><br>private tailrec fun factorialWithAccumulator(<br>    num: Int,<br>    accumulator: Int<br>): Int {<br>    return if (num &lt;= 0) {<br>        accumulator<br>    } else {<br>        factorialWithAccumulator(num - 1, accumulator * (num))<br>    }<br>}</pre><p>Have functional fun! 🥳</p><h4>Resources:</h4><ul><li><a href="https://fpsimplified.com/">Functional programming simplified</a></li><li><a href="https://www.youtube.com/watch?v=I8LbkfSSR58&amp;list=PLbgaMIhjbmEnaH_LTkxLI7FMa2HsnawM_">Category Theory</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=306f0a1170f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Art of Recursion.]]></title>
            <link>https://kinya.medium.com/the-art-of-recursion-1d41a6160b5c?source=rss-90181ab7429f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d41a6160b5c</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Beatrice Kinya]]></dc:creator>
            <pubDate>Thu, 01 Aug 2024 14:17:05 GMT</pubDate>
            <atom:updated>2024-08-14T15:54:27.130Z</atom:updated>
            <content:encoded><![CDATA[<h4>Writing Elegant Code with Functional Programming</h4><blockquote>Function programming — where algebra meets code.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JFR36vgh_Mnq--ssCl1pqA.jpeg" /><figcaption>Photo Taken by Author</figcaption></figure><p>Modern programming languages are increasingly embracing functional programming patterns. Some languages, like Haskell, are purely functional while most incorporate functional features to varying extents. For instance, higher-order functions and lambda expressions in Kotlin.</p><p>Functional programming is about creating software programs using <strong>pure functions </strong>and <strong>immutable values</strong>. What are pure functions, you ask?</p><p>A pure function is a function that when called with input x an infinite number of times its output will always be y . For example the add(a, b) function:</p><pre>fun add(a: Int, b: Int): Int {<br>    return a + b<br>}</pre><p>add(a, b) function will always return the sum of the two numbers passed as arguments.</p><h4>Recursion</h4><p>Recursion is one of the core techniques applied in functional programming. Why recursion, you may wonder.</p><p>Consider a function that calculates the sum of integers in a list. Intuitively, you’d write code like this:</p><pre>fun sum(nums: List&lt;Int&gt;): Int{<br>    var result = 0<br>    for (i in nums){<br>        result += i<br>    }<br>    return result<br>}</pre><p>The above code works perfectly fine. However, it uses a mutable variable, var result. Immutable values are preferred since using immutable values makes the behavior of your programs far more predictable.</p><p>To achieve immutability in the sum function, you’ll write the sum function using recursion. Ready, steady…</p><p>When writing a recursive function, you’d follow these three steps:</p><p><strong>Determine the Function Signature</strong></p><p>The sum function takes a list of integers as input and returns the sum of the integers. Hence, its output is a single value of type Int . The function signature will look like this:</p><pre>fun sum(nums: List&lt;Int&gt;): Int = ???</pre><p><strong>Determine the Base Case</strong></p><p>This is the simplest form of the problem that can be solved without recursion. This usually marks the end condition, e.g. an empty list.</p><p>If the sum function is called with an empty list, the function should return 0 .</p><pre>fun sum(nums: List&lt;Int&gt;): Int =<br>    if (nums.isEmpty()) {<br>        0<br>    }else ???</pre><p><strong>Write the Algorithm</strong></p><p>If the sum function is called with a list of integers the output of the function will be the combination first value in the list and the sum of the remaining values.</p><p>For instance, if the function is called with [2, 3, 4, 5] — sum([2, 3, 4, 5]) — its output will be a combination of the first integer, 2 , and the sum of the remaining of the remaining integers. Like this: 2 + sum([3, 4, 5])</p><p>Now, you can write the remaining part of the function. The complete function will look like this:</p><pre>fun sum(nums: List&lt;Int&gt;): Int =<br>    if (nums.isEmpty()) {<br>        0<br>    } else {<br>        nums[0] + sum(nums.drop(1))<br>    }</pre><p>Fantastic! You have a recursive function to calculate the sum of a list of integers. No mutable variables ( var ‘s ). This makes the code much easier to reason about, isn’t it?</p><h4>Bonus</h4><p>A function to calculate the factorial of an integer using recursion:</p><pre>fun factorial(num: Int): Int =<br>    if (num == 0) {<br>        1<br>    } else {<br>        num * factorial(num - 1)<br>    }</pre><p>Recursion creates a stack of frames (<em>more about this in the next section). </em>For algorithms that require deep levels of recursions, this will lead to StackOverFlowError and cause your application to crash.</p><p>Good news! Kotlin supports <strong>tail-recursion</strong>. This technique enables you to write recursive functions without the risk of stack overflow. Know your way around JVM stacks? Then you can skip the next bit, <a href="https://kinya.medium.com/tail-recursion-306f0a1170f4">tail recursion</a>.</p><h4>JVM Stacks and Stack Frames</h4><p>A JVM stack is created when a new thread is launched. The stack is also called a <em>call stack</em>. The stack stores thread state in discreet frames, known as stack frames. A stack frame is created every time a new method is called. The JVM only pops and pushes the stack frames.</p><blockquote>Check <a href="https://www.artima.com/insidejvm/ed2/jvm8.html">Inside the Java Virtual Machine</a> to for more about JVM stacks and stack frames</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*rNF1EDtXaCdlQDBDWO_11A.png" /></figure><p>Let’s see how the recursive sum function from earlier the stack frames are added to the JVM stack.</p><p>The sum function is called from the main function:</p><pre>fun sum(nums: List&lt;Int&gt;): Int =<br>    if (nums.isEmpty()) {<br>        0<br>    } else {<br>        nums[0] + sum(nums.drop(1))<br>    }<br><br><br>fun main() {<br>    val sum = sum(listOf(11, 27, 31))<br>        ...<br>}</pre><p>When the main is executed, it’ll be the first one to be added to the call stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/1*hbCgiwm8CuZ7bfY_TWD3Ng.png" /></figure><p>Then the main function calls the sum function with [11, 27, 31] . sum([11, 27, 31]) is added to the call stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/209/1*XECSLYG_cKJ3pdGpqsx6Iw.png" /></figure><p>The else block matches and the function is evaluated like this:</p><pre>11 + sum([27, 31])</pre><p>A new instance of sum with [27, 31] is added to the call stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/209/1*c8gPiAZLXF3BXuDBVnEW9w.png" /></figure><p>Again the else block matches and the function is evaluated like this:</p><pre>27 + sum([31])</pre><p>A new instance of sum with [31] is added to the call stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*WxN0PNV6HUaF51fWDcACBw.png" /></figure><p>For the third case, the else block matches, and the function is evaluated like this:</p><pre>31 + sum([])</pre><p>Eventually, another instance of sum with an empty list is added to the call stack. The stack now looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*lPcys54MeXZTwg5wC2QP-A.png" /></figure><p>When the sum function is called with an empty list, the end condition is reached, and the function returns zero. The stack frames are popped out of the stack. In the process, each call to the sum function returns its result. Finally, the sum function returns 69 to the main function where it was first called.</p><p>The unwinding looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*Isf6uTV6mXKMqq0CqUEXBQ.jpeg" /></figure><p>This looks algebraic, isn’t it?</p><p>The stack frames will be popped from the stack like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7JxOgdeYqUL_l1IRJDuBlA.png" /></figure><p>A stack overflow occurs when you’ve used up more memory for the stack than your program was supposed to use. If you do not specify the size, the memory size will be the default size depending on the operating system and computer architecture.</p><p>To check the JVM stack default size on a Linux-based system, you’d use this command.</p><pre>java -XX:+PrintFlagsFinal -version | grep ThreadStackSize</pre><p>Kotlin can handle deep recursion without running into stack overflow issues. See <a href="https://kinya.medium.com/tail-recursion-306f0a1170f4">this article</a> on how to make the sum function tail-recursive.</p><h4>Resources</h4><ul><li><a href="https://fpsimplified.com/">Functional programming simplified</a></li></ul><p>Have functional fun! 🥳</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d41a6160b5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pattern Matching Magic]]></title>
            <link>https://kinya.medium.com/pattern-matching-magic-8793610779c3?source=rss-90181ab7429f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8793610779c3</guid>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[pattern-matching]]></category>
            <dc:creator><![CDATA[Beatrice Kinya]]></dc:creator>
            <pubDate>Sun, 17 Mar 2024 16:22:54 GMT</pubDate>
            <atom:updated>2024-03-20T05:53:40.695Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ZIzkGOCnJyK7CtwuO5L_w.jpeg" /><figcaption>image by <a href="https://www.pexels.com/@fwstudio-33348/">fwstudio</a> on pexels.com</figcaption></figure><h4>A Tour for JVM Developers.</h4><p>I’m still exploring the JVM universe, and Scala has become my buddy. Together, we unlock the power of <strong>pattern matching</strong>, one of its handy features.</p><p>Pattern matching is checking a value against a pattern. The pattern could be a constant, a variable, a constructor of a case class or even more complex combinations. A successful match can deconstruct a value into its constituent parts. This can be used in place of a series of if/else statements.</p><p>Scala uses match expressions for pattern matching. For example matching a number to a month of the year:</p><pre>val monthIndex: Int = 7<br>val month: String = monthIndex match<br>  case 1 =&gt; &quot;January&quot;<br>  case 2 =&gt; &quot;February&quot;<br>  case 3 =&gt; &quot;March&quot;<br>  case 4 =&gt; &quot;April&quot;<br>  case 5 =&gt; &quot;May&quot;<br>  case 6 =&gt; &quot;June&quot;<br>  case 7 =&gt; &quot;July&quot;<br>  case 8 =&gt; &quot;August&quot;<br>  case 9 =&gt; &quot;September&quot;<br>  case 10 =&gt; &quot;October&quot;<br>  case 11 =&gt; &quot;November&quot;<br>  case 12 =&gt; &quot;December&quot;<br>  case _ =&gt; &quot;Not A month&quot; // Default case</pre><p>monthIndex is an integer representing index of a month of the year. It is the left operand of the match expression. On the right side, there are all possible cases of months starting January till December. The last case represented by _ is a “catch all” case for any other possible Int values.</p><p>Scala match expression offers a rich set of pattern matching capabilities: simple constants comparisons as in the example above and can handle sequences, tuples, type checks and constructor structures. My favourite is constructor pattern matching. Leveraging the structure of a case class and using constructor pattern matching you’d check the type of value as well as extract fields of the object, all in a single match expression.</p><blockquote>Check out <a href="https://medium.com/p/07e0e3bf2602#7d31">Destructuring Assignment</a> article to learn more about unpacking values of an object to variables.</blockquote><p>Using a Student example:</p><pre>sealed trait Student<br><br>case class Undergrad(name: String, course: String, studyMode: String) extends Student<br><br>case class GradStudent(name: String, course: String) extends Student</pre><p>Student is a sealed trait with two concrete implementations: Undergrad and GradStudent. Now, you’d match an instance of Student like this:</p><pre>def simpleMatching(student: Student): String = {<br>  student match<br>    case Undergrad(name, courseName, studyMode) =&gt;<br>      s&quot;$name is undergrad student pursuing $courseName as a $studyMode student&quot;<br>    case GradStudent(name, courseName) =&gt; <br>      s&quot;$name is a grad student pursuing $courseName&quot;<br>}<br><br><br>val student = Undergrad(&quot;Bilbo&quot;, &quot;Scala&quot;, &quot;FullTime&quot;)<br>val result = simpleMatching(student)<br>println(result) // Prints &#39;Bilbo is a undergrad student pursuing Scala as a FullTime student&#39;<br></pre><p>What about when you have a nested data structure?</p><p>Consider the following:</p><pre>sealed trait Course<br><br>case class SoftwareEngineering(track: String, name: String)<br><br>case class MachineLearning(name: String)<br><br><br>sealed trait Student<br><br>case class Undergrad(name: String, course: Course, studyMode: String) extends Student<br><br>case class GradStudent(name: String, course: Course) extends Student</pre><p>A Course is a sealed trait. It has two implementations: Software Engineering and Machine Learning . Every Student implementation has a Course property.</p><p>You’d like to match all undergrad students taking software engineering in the mobile track and graduate students taking Machine learning.</p><h4>Deconstructing values</h4><p>In Scala, when a pattern successfully matches a value, any variables defined within the pattern become <strong>bound</strong> to the corresponding parts of the matched value. This allows you to access specific components of a data structure without needing property look ups, with getter methods for instance.</p><p>Using deconstructing values feature, then you’d to write a match expression like this:</p><pre>def complexMatching(student: Student): String = {<br>  student match<br><br>    case Undergrad(name, SoftwareEngineering(&quot;Mobile&quot;, courseName), _) =&gt;<br>      s&quot;$name is on Mobile track pursuing $courseName&quot;<br><br>    case GradStudent(name, MachineLearning(courseName)) =&gt;<br>      s&quot;$name is a Machine Learning student pursuing $courseName&quot;<br><br>    case _ =&gt; &quot;Other Students&quot;<br>}</pre><p>Deconstructing values with pattern matching allows you to extract values from complex data structures while writing concise, expressive and safer code.</p><h4>PS: Kotlin</h4><p>Kotlin is defintely my favourite language. Won’t it be great to be able implement complex pattern matching using the language?</p><p>Kotlin does not support full-blown pattern matching, yet. If you have complex data type involving deconstructing values, you’d use traditional if-else statements or nested when expressions.</p><p>Using the Studnet example from above:</p><pre>sealed interface Course<br>data class SoftwareEngineering(val track: String, val courseName: String): Course<br>data class MachineLearning(val courseName: String): Course<br><br>sealed interface  Student<br>data class UnderGradStudent(val name: String, val course: Course, val studyMode: String) : Student<br>data class GradStudent(val name: String, val course: Course): Student</pre><p>To match undergraduate students taking software engineering on the mobile track and graduate students taking Machine learning, you’ll write code like this:</p><pre>fun filterStudents(student: Student): String{<br>  return when(student){<br><br>        is UnderGradStudent  -&gt; {<br>            val (name, course, _) = student<br>            when(course){<br><br>                is SoftwareEngineering -&gt; {<br>                    if (course.track == &quot;Mobile&quot;) {<br>                        &quot;$name is in Mobile track pursuing ${course.courseName}&quot;<br>                    }else{ &quot;Other students&quot; }<br>                }<br>                else -&gt; { &quot;Other Students&quot; }<br>            }<br>        }<br><br>        is GradStudent -&gt;{<br>            val(name, course,) = student<br>            when(course){<br>                is MachineLearning -&gt; {<br>                    &quot;$name is a Machine learning student pursuing ${course.courseName}&quot;<br>                }<br>                else -&gt; { &quot;Other Students&quot;}<br>            }<br>        }<br>    }<br>}</pre><p>This code is less expressive, a little more verbose? It would benefit from destructuring values feature. Then you’d write code like this:</p><pre>fun filterStudents(student: Student): String{<br>  return when(student){<br>        is UnderGradStudent(name, SoftwareEngineering(&quot;Mobile&quot;, courseName),_ ) -&gt; { }<br>        is GradStudent(name, MachineLearning(courseName)) -&gt;{ }<br>        else -&gt; { }<br>    }<br>}</pre><p>Potentially, pattern matching with complex types is coming to Kotlin. Check this: <a href="https://youtrack.jetbrains.com/issue/KT-186/Support-pattern-matching-with-complex-patterns">Support for pattern matching with complex patterns</a>. And one day, you’d match complex data structures while still maintaining concise and expressive code. 🙌🏽</p><h4>Resources</h4><ul><li><a href="https://docs.scala-lang.org/tour/pattern-matching.html#:~:text=Pattern%20matching%20is%20a%20mechanism,series%20of%20if%2Felse%20statements.">Pattern matching in Scala</a></li><li><a href="https://docs.scala-lang.org/scala3/book/control-structures.html#match-expressions">Match Expression in Scala</a></li></ul><p>Fun coding! Or there and back again.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8793610779c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Destructuring Assignment, Nested deconstruction — Part 2/2]]></title>
            <link>https://kinya.medium.com/destructuring-assignment-nested-deconstruction-part-2-2-6f4e32628ae0?source=rss-90181ab7429f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f4e32628ae0</guid>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[Beatrice Kinya]]></dc:creator>
            <pubDate>Mon, 04 Mar 2024 09:33:14 GMT</pubDate>
            <atom:updated>2024-03-04T09:41:59.018Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mPPLAYIdi6fmpQmeEO4XHw.jpeg" /><figcaption>source: pexels.com</figcaption></figure><h3>Destructuring Assignment, Nested destructuring — Part 2/2</h3><p>In the first article, <a href="https://kinya.medium.com/destructuring-assignment-kotlin-vs-scala-07e0e3bf2602">Destructuring assignment — Part 1/ 2</a>, I compared how destructuring assignment works in Kotlin and Scala. How about nested object destructuring? You mighty ask😃.</p><p>Consider the following Kotlin code:</p><pre>data class Course(val courseId: String, val name: String)<br>data class Student(val name: String, val course: Course)</pre><p>How would you destruct an object of Student class? Doing this produces compile time errors.</p><pre><br>val course = Course(name = &quot;Kotlin course&quot;, courseId = &quot;KT&quot;)<br>// Create an object of Student class<br>val student = Student(name = &quot;Kotlin student&quot;, course = course)<br><br>// Destructuring assignment<br>// This produces compile time errors<br>val (studentName, (courseId, courseName)) = student</pre><p>How about Scala?</p><p>Consider the following:</p><pre>case class Course( val courseId: String, val name: String)<br>case class Student(val name: String, val course: Course )<br><br>val course = Course(courseId = &quot;SC&quot;, name = &quot;Scala course&quot;)<br>// Create an object of student class<br>val student = Student(name= &quot;Scala student&quot;, course = course)</pre><p>Then you can deconstruct student object like this:</p><pre>val Student (studentNme: String, Course(courseId, courseNme: String)) = student</pre><p>And use individual variables independently:</p><pre>println(s&quot;Student name =&gt; $studentName&quot;)<br>println(s&quot;Course Name =&gt; $courseName&quot;)</pre><p>Case classes in Scala are assumed to be immutable. The Scala compiler generates helpful methods like apply , unapply , copy , equals and hashCode for you. unapply method is used in deconstruction of respective objects.</p><p>This line of code:</p><pre> val Student (studentName: String, Course(_, courseName: String)) = student</pre><p>is compiled to:</p><pre>val studentName = Student.unapply(student).get._1<br>val courseId = Course.unapply(course).get._1<br>val courseName = Course.unapply(course).get._2</pre><p>Kotlin on the other hand uses componentN function to unpack values from an object.</p><p>To extra values from an object of the Student class, you’d do this</p><pre>data class Student(val name: String, val course: Course)<br><br>val course = Course(name = &quot;Kotlin course&quot;, courseId = &quot;KT&quot;)<br>// Create an object of Student class<br>val student = Student(name = &quot;Kotlin student&quot;, course = course)<br><br>// Extract values from the student object<br>val (studentName, courseDestruct) = student<br>// Extract values from the course object<br>val (courseId, courseName) = courseDestruct</pre><p>When you look at the byte code for the Student class, you’ll see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c6HLqdDhlpzid4daapuROg.png" /></figure><p>Then this code:</p><pre>val (studentName, courseDestruct) = student</pre><p>is compiled to:</p><pre>val studentName = student.component1()<br>val courseDestruct = student.component2()</pre><h3>Conclusion</h3><p>Kotlin and Scala share fundamental similarities in nested destructuring. There are subtle variations too. In syntax and pattern matching capabilities. We’ll explore pattern matching in a future article 😃. Selecting the appropriate language depends on your specific project requirements and preferences. If you value a concise and familiar destructuring syntax, Kotlin might be a good choice. On the other hand, if you need more powerful pattern matching functionalities, Scala could be a more suitable option.</p><p>Happy Coding! 🙌🏽</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f4e32628ae0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Destructuring Assignment- Kotlin vs Scala]]></title>
            <link>https://kinya.medium.com/destructuring-assignment-kotlin-vs-scala-07e0e3bf2602?source=rss-90181ab7429f------2</link>
            <guid isPermaLink="false">https://medium.com/p/07e0e3bf2602</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[jvm]]></category>
            <dc:creator><![CDATA[Beatrice Kinya]]></dc:creator>
            <pubDate>Mon, 12 Feb 2024 07:27:16 GMT</pubDate>
            <atom:updated>2024-03-17T15:18:36.971Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mPPLAYIdi6fmpQmeEO4XHw.jpeg" /><figcaption>source: pexels.com</figcaption></figure><h3>Destructuring Assignment, Kotlin vs Scala — Part 1/ 2</h3><p>Most recently, I started learning Scala. Scala is a JVM language. As you’d expect, there are similarities with other JVM languages like Kotlin and Java. And differences here and there.</p><p>Both Kotlin and Scala provide a destructuring assignment feature. Destructuring enables extracting values from a data structure. For instance, data classes in Kotlin. This promotes conciseness in code by avoiding repetitive value extractions.</p><blockquote>Java has not been left behind. <a href="https://openjdk.org/jeps/443">In Java 21</a>, you can deconstruct fields of a java record. Find more <a href="https://bijukunjummen.medium.com/destructuring-in-java-and-kotlin-0de084268a53">here</a>.</blockquote><p>Each language implements destructuring differently from the other one.</p><p>Kotlin’s destructuring declarations allow you to extract fields from an object to a set of variables.</p><pre>data class Student(val name: String, val studentId: Int, val score: Double)<br><br>// Create an object of a Student<br>val student = Student(name = &quot;Kotlin student&quot;, studentId = 91250, score = 99.00)<br><br>// Destructuring declaration<br>val (name, studentId, score) = student</pre><p>Then you can use variables independently in any way out.</p><pre>println(&quot;Student name is $name&quot;)<br>println(&quot;Student Id is $studentId&quot;)<br>println(&quot;Student score is $score&quot;)</pre><p>Under the hood, the compiler uses componentN operator functions to unpack values of an object and assign them to the variables.</p><p>The destructive declaration above is compiled to:</p><pre>val name = student.component1()<br>val studentId = student.component2()<br>val score = student.component3()</pre><p>Kotlin’s destructuring declarations provide a powerful and concise way to extract and assign values from <strong>pairs and data classes</strong>.</p><p>You could make a class support destructuring declarations. By adding componentN operator function to the class:</p><pre>class Employee(<br>    val name: String,<br>    val employeeId: String<br>) {<br>    operator fun component1(): String = name<br>    operator fun component2() : String = employeeId<br>}</pre><p>Then deconstruct it like this:</p><pre>val employee = Employee(&quot;Kotlin Employee&quot;, &quot;EmployeeA1&quot;)<br><br>val(employeeName, employeeId) = employee<br><br>println(&quot;Employee name is $employeeName&quot;)<br>println(&quot;EmployeeId is $employeeId&quot;)</pre><p>component2 is used to extract the second element. If you want to extract the third element, you’ll add component3 operator method, and so on.</p><p>This is quite intuitive, isn’t it?</p><p>Probably, like me, you’re wondering. How would I implement destructuring assignment in Scala?</p><p>Scala uses unapply() method. To understand how the method works, let’s look at <strong>extractor objects</strong>.</p><h3>Scala Extractor Objects</h3><p>Extractor objects are objects used to deconstruct an object in a consice and flexible manner. Every extractor object has unapply() method. unapply() method extracts values compacted in an object and returns back the attributes.</p><p>For instance, Student class:</p><pre>class Student(val name: String, val studentId: Int, val score: Float)</pre><p>Then StudentCompanion extractor object looks like this:</p><pre>object StudentCompanion:<br>  // 1<br>  def apply(name: String, studentId: Int, score: Float) =<br>    new Student(name, studentId, score)<br>  // 2<br>  def unapply(student: Student): Option[(String, Int, Float)] =<br>    Some(student.name, student.studentId, student.score)</pre><ol><li>apply() method creates an instance of Student from the parameters name , studentId and score.</li><li>unapply() method deconstructs the student object and returns student’s name, studentId and score.</li></ol><p>We can now use destructuring assignment like this:</p><pre>// Create an object of Student <br>val student = Student(&quot;Scala Student&quot;, 91250, 99.00)<br><br>// Destructuring assignment<br>val StudentCompanion(name, studentId, score) = student<br><br>// Use the variables indepently<br>println(s&quot;Student name =&gt; $name&quot;)<br>println(s&quot;Student ID =&gt; $studentId&quot;)<br>println(s&quot;Student&#39;s Score is $score&quot;)</pre><p>This assignment:</p><pre>val StudentCompanion(name, studentId, score) = student</pre><p>is compiled to:</p><pre>val name = StudentCompanion.unapply(student).get._1<br>val studentId = StudentCompanion.unapply(student).get._2<br>val score = StudentCompanion.unapply(student).get._3</pre><p>unapply() method works if you want to deconstruct values of an object to a set of single-value items. If you want to deconstruct an object to a collection of extracted values you’d use unapplySeq() method.</p><pre>class HobbitName(val firstName: String, val lastName: String)<br><br>object HobbitCompanion:<br>  def unapplySeq(hobbit: HobbitName): Option[List[String]]= {<br>    Option(List(hobbit.firstName, hobbit.lastName))<br>  }</pre><p>Then we can deconstruct HobbitName to a list of its constituent names:</p><pre>val hobbitName = HobbitName(firstName = &quot;Bilbo&quot;, lastName = &quot;Baggins&quot;)<br><br>val HobbitCompanion(firstName: String, lastName: String) = hobbit<br><br><br>println(s&quot;firstName =&gt; $firstName&quot;)<br>println(s&quot;lastname =&gt; $lastName&quot;)</pre><h4>Case classes</h4><p>A case class is used for modelling immutable data. For example, Student class:</p><pre>case class Student(name: String, studentId: String, score: Float)</pre><p>The Scala compiler generates helpful methods like apply , unapply , copy , equals and hashCode for each case class .unapply method is used in deconstructing respective objects.</p><p>To extra values from an object of the Student class, you’d write code like this:</p><pre>val student = Student(&quot;Bilbo&quot;, &quot;Y19BBN&quot;, 3.75)<br>val Student(name, studentId, score ) = student<br>    <br>println(studentId) // prints Y19BBN</pre><h3>Conclusion</h3><p>Both Kotlin and Scala support destructuring assignement.</p><p>Kotlin uses componetN functions to unpack fields of an object and assign them to individual properties.</p><p>Scala on the other hand uses unapply() method to deconstruct an object. This is most often used in pattern matching and partial functions.</p><p>Fun coding! Or There and Back again 😃.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07e0e3bf2602" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>