<?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 Alberto Ballano on Medium]]></title>
        <description><![CDATA[Stories by Alberto Ballano on Medium]]></description>
        <link>https://medium.com/@aballano?source=rss-14e6209c1c05------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3p2HW_OF7Ny2DNCtRLFmIQ.png</url>
            <title>Stories by Alberto Ballano on Medium</title>
            <link>https://medium.com/@aballano?source=rss-14e6209c1c05------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 21:48:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aballano/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[Moving Medium to Github.io]]></title>
            <link>https://medium.com/@aballano/moving-medium-to-github-io-54672dd787ae?source=rss-14e6209c1c05------2</link>
            <guid isPermaLink="false">https://medium.com/p/54672dd787ae</guid>
            <category><![CDATA[github-pages]]></category>
            <category><![CDATA[goodbye]]></category>
            <category><![CDATA[medium]]></category>
            <dc:creator><![CDATA[Alberto Ballano]]></dc:creator>
            <pubDate>Fri, 03 Mar 2023 22:19:41 GMT</pubDate>
            <atom:updated>2023-03-03T22:30:39.683Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KpNvNBcJFV1IbCWySheTqw.png" /><figcaption>Image courtesy of Dall-e</figcaption></figure><p>Hello there 👋</p><p>It’s been a while, isn’t it? Almost 5 years since my last <a href="https://tech.new-work.se/dealing-with-rxjavas-never-ending-observables-1ca8f18797ff">post</a>…</p><p>I’ll be brief, but the good news, as the title says, is that I’m moving my “blog” to <a href="https://aballano.github.io/">https://aballano.github.io/</a> where I have full control of the content, style and who can see my posts without having to go incognito due to “paywalls” :)</p><p>So, that’s it, I hope to migrate all of the old posts step by step, you can already take a look at the <a href="https://aballano.github.io/never-ending-observables/">latest one</a> which I already migrated.</p><p>I’ll try to continue posting experiences, ideas and small projects, hope you read and enjoy them!</p><p>P.S. Here’s an almost-used text by Chat-GPT, how good was it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k9hZBsAaQV9Cb93Z2UObsA.png" /></figure><p>Cheers, Me 🤘 😂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54672dd787ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dealing with RxJava's never-ending Observables]]></title>
            <link>https://tech.new-work.se/dealing-with-rxjavas-never-ending-observables-1ca8f18797ff?source=rss-14e6209c1c05------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ca8f18797ff</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Alberto Ballano]]></dc:creator>
            <pubDate>Mon, 04 Jun 2018 04:06:01 GMT</pubDate>
            <atom:updated>2018-07-12T17:29:05.958Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D_e9MRnBqYipvdJO.png" /></figure><p>Never-ending Observables are those that observe some data indefinitely until you unsubscribe from them. They&#39;re quite useful in many situations, specially when dealing with databases as you can observe emissions from a specific table, for example. A good example of this is <a href="https://github.com/square/sqlbrite">SqlBrite</a>.</p><p>When using this kind of observables we need to take care on which operators to use on them since you might run into problems. This is specially dangerous if you, for example, want to migrate DB query using Single to an Observable, because the operators don&#39;t always work the same way…</p><h3>The scenario</h3><p>Let’s imagine this simple* case:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f858b2e8d884b19ba015a131c0efe15/href">https://medium.com/media/1f858b2e8d884b19ba015a131c0efe15/href</a></iframe><p>(*This can be solved in other ways, but it&#39;s just for simplicity purposes)</p><p>Now a typical test could be as following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fb3e0ec547e3b23c188d52e7a8c9942/href">https://medium.com/media/6fb3e0ec547e3b23c188d52e7a8c9942/href</a></iframe><h4>Now is QUIZZ time! What will this test output?</h4><p>a) Failure<br>b) Success</p><h3>The problem</h3><p>If you answered the second, you’re right: this test will pass even though the <strong>production code is wrong</strong>!</p><blockquote>“Wait, what?? But my test just passed!”</blockquote><p>Indeed it does! But why? This is a bad combination of using the <strong>wrong operator</strong> and the <strong>wrong test</strong> implementation.</p><p>Let&#39;s first take a look at our test and figure it out why <strong>it&#39;s passing when it should be failing</strong>!</p><h4>The wrong testing approach</h4><p>Ok, so at this point we might have discovered that our app doesn&#39;t really work when running this code, but our tests say the other way, so where&#39;s the catch?</p><p>As stated in the getUserList() function comment:</p><p>//some DB query observing changes</p><p>This means that, for this specific case of Observing DB changes, you need an Observable that will emit, via onNext the initial value and all subsequent values <strong>every time</strong> the DB is updated. This means that this observable will <strong>never complete</strong>.</p><p>Then, if you take a closer look at our test you could spot the problem:</p><pre>whenever(localDataSource.observeUserList())<br>    .thenReturn(Observable.just(USER_LIST))</pre><p>Again, just checking the docs this time, you could see that Observable.just emits a single value and then <strong>completes</strong>! This mean that our test scenario is not the same as our real scenario, since we would need an observable that never completes. Luckily this has an easy fix by creating a utility function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c4a05134f5e29925a157f3e6ca72520/href">https://medium.com/media/3c4a05134f5e29925a157f3e6ca72520/href</a></iframe><p>Alternatively you could also use an Rx Subject (thanks <a href="https://medium.com/u/7c311e3f4a6a">pacoworks</a> for the hint).</p><p>Ok, so our test now matches our real scenario and now we can see it <strong>failing</strong>! Now the question is, why?</p><h4>The wrong operator</h4><p>The answer will look simple for the ones that already noticed or had problems with this before:</p><p>An observable that never completes cannot be used with <strong>certain operators</strong>, as some of them require the observable to actually <strong>complete</strong> in order to do their job. An example of that is the toList() operator that we&#39;re using. Taking a look inside we can see this piece of code:</p><pre>@Override<br>public void onNext(T t) {<br>    collection.add(t);<br>}</pre><pre>(...)</pre><pre>@Override<br>public void onComplete() {<br>    U c = collection;<br>    collection = null;<br>    actual.onSuccess(c);<br>}</pre><p>So this makes quite clear that the toList() operator only works on Observables that <strong>have an end</strong> (which, by the way, seems pretty obvious once you think about it).</p><p>Fixing this specific case shouldn&#39;t be too difficult as you could map the list directly if you&#39;re using Kotlin or play around with conversions to Single using the firstOrError() operator on the given observable, example:</p><pre>getUserList()<br>    // Get the first emission (List&lt;User&gt;)<br>    <strong>.firstOrError()<br>    </strong>// Now fallback to Observable as Single doesn&#39;t                            <br>    // have flatMapIterable<br>    <strong>.toObservable() </strong><br>    // Transform into Observable&lt;User&gt; with multiple emissions<br>    .flatMapIterable <strong>{ it }<br>    </strong>.map <strong>{ </strong>user <strong>-&gt; </strong>user.name <strong>}<br>    </strong>.toList()</pre><p>Or even simpler if you use Kotlin&#39;s map:</p><pre>getUserList()<br>    // List&lt;User&gt; -&gt; List&lt;String&gt;<br>    .map { it.<em>map </em>{ it.name } }<strong><br>    </strong>// Get the first emission<strong><br>    </strong>.firstOrError()</pre><h3>Recap</h3><p>Messing with Rx if we don&#39;t really know what an operator does or what kind of Observable we have (finite or never-ending) is relatively easy and that combined to a wrong test implementation could lead to errors in production. For that I have two tips:</p><p>1- Try to identify the type of your Observable:</p><ul><li>If it&#39;s a finite one (one that completes) use Observable.just for your tests.</li><li>If it&#39;s an infinite/never-ending one (one that doesn&#39;t complete) use Observable.create as shown.</li></ul><p>2- In order to avoid this issues with RxJava is always good to <strong>take a look to the docs</strong>, even if you think you know what you’re doing.</p><p>Hope you liked or learned something new with this article, if so please hit the clap button below.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ca8f18797ff" width="1" height="1" alt=""><hr><p><a href="https://tech.new-work.se/dealing-with-rxjavas-never-ending-observables-1ca8f18797ff">Dealing with RxJava&#39;s never-ending Observables</a> was originally published in <a href="https://tech.new-work.se/">New Work Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Delimiting your app boundaries with Kotlin's sealed classes]]></title>
            <link>https://medium.com/@aballano/delimiting-your-app-boundaries-with-kotlins-sealed-classes-cd7c40974078?source=rss-14e6209c1c05------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd7c40974078</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Alberto Ballano]]></dc:creator>
            <pubDate>Thu, 22 Feb 2018 13:35:30 GMT</pubDate>
            <atom:updated>2018-05-31T13:15:20.349Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*fEs5MAJuiwW1gre5StGh5g.png" /></figure><p>Some of us might run into a common problem when having to present data to the user. That is, encoding real life&#39;s boundaries into a language that might not reflect reality as we see it.</p><p>Imagine that we have a view with a presenter and we want to initialize this one with an User&#39;s info and display some data, we would have the following model:</p><pre>data class User(<br>    val id: String, <br>    val name: String, <br>    val surname: String<br>)</pre><p>And the presenter:</p><pre>fun showUserInfo(user: User) {<br>    <em>displayUserName</em>(user.name)<br>    <em>displayUserSurname</em>(user.surname)<br>    //(...)<br>}</pre><p>This code is fine; we have our preloaded user, so we just show their information to the user. But what happens when we navigate from a deep link or somewhere else where we don&#39;t have the full user but its ID? What if we need to fetch it first? We would have this case:</p><pre>fun showUserInfo(id: String) {<br>    val user = <em>fetchUser</em>(id)<br>    // we ignore the threading part <br>    // as it&#39;s irrelevant for the purpose of the article<br>    <em>displayUserName</em>(user.name)<br>    <em>displayUserSurname</em>(user.surname)<br>    //(...)<br>}</pre><p>To make this distinction, we need an initialization point from where to call from the view, to reduce the amount of logic it contains. Let&#39;s also do a small refactor to remove this last function to reduce the amount of duplicated code. The result is as follows:</p><pre>fun init(id: String?, user: User?) {<br>    val validUser: User = when {<br>        id != null -&gt; <em>fetchUser</em>(id)<br>        user != null -&gt; user<br>    }<br><br>    <em>showUserInfo</em>(validUser)<br>}<br><br>private fun showUserInfo(user: User) {<br>    <em>displayUserName</em>(user.name)<br>    <em>displayUserSurname</em>(user.surname)<br>    //(...)<br>}</pre><p>As you can see, there are several problems with this approach:</p><ul><li>This is not pretty, as the view implementation or whoever calls init needs to pass a parameter while making the other explicitly null (we could benefit from default parameters here, but it will lead to the same next problem)</li><li>There&#39;s one case missing! That code won&#39;t compile because what happens if you pass two nulls here? Is that a real case scenario anyway? We need to change the when statement to this:</li></ul><pre>when {<br>    id != null -&gt; <em>fetchUser</em>(id)<br>    user != null -&gt; user<br>    else -&gt; crashWithInvalidDataException()<br>}</pre><p>Ok, so 5 lines in our new shiny class and we&#39;re already crashing for a case that &quot;should never happen&quot;, not too good :(</p><h4>But this won&#39;t happen in a real case scenario!</h4><p>Yes, we &quot;all&quot; know, right? Still, this implementation (and probably the tests too) <strong>tells a different story</strong>. What do you think will happen when a new person in your team reads this code? Are you gonna start explaining all occurrences of this kind of solution as part of the onboarding plan?</p><p>There&#39;s an apparent <strong>mismatch about what the real specification is and what the code is doing</strong>, and that leads to potential errors that &quot;should never happen&quot;, although they sometimes do, and to useless boilerplate code or exceptions thrown meant to cover this lack of boundaries of your system.</p><h4>Defining your program boundaries</h4><p>Some of you might have be thinking of the perfect Kotlin tool to solve this issue, and for the ones that didn&#39;t yet, let&#39;s try to put that thought in your brain :)</p><p>Whenever I find myself in this kind of situations where real life have some boundaries that cannot be expressed easily in code. A magical, beautiful words come to my mind: sealed class</p><p>Yes! Sealed classes, because they have all we need for these scenarios: limited boundaries (such as enums) and a variety of parameters.</p><p>Let&#39;s start defining our boundaries first, we can have either an already fetched User or an id, so here we go:</p><pre>sealed class UserData {<br>    data class Model(val user: User) : UserData()<br>    data class Id(val id: String) : UserData()<br>}</pre><p>Easy, right? Now let&#39;s modify our init function</p><pre>fun init(userData: UserData) {<br>    val validUser: User = when(userData) {<br>        is UserData.Model -&gt; userData.user<br>        is UserData.Id -&gt; <em>fetchUser</em>(userData.id)<br>    }<br><br>    <em>showUserInfo</em>(validUser)<br>}</pre><p>And we&#39;re done! Not only we managed to remove the else case, but we also made our code more bulletproof and readable.</p><p>Hope you enjoyed the article, feel free to add suggestions as comments or via <a href="https://twitter.com/aballano">twitter</a>.</p><p>Happy coding!</p><p>P.S. Thanks <a href="https://medium.com/u/b276785d55d2">pablisco</a> for proofreading the article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd7c40974078" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reactive Functional Presenters: Handling Typing notifications.]]></title>
            <link>https://tech.new-work.se/reactive-functional-presenters-handling-typing-notifications-15a514b67077?source=rss-14e6209c1c05------2</link>
            <guid isPermaLink="false">https://medium.com/p/15a514b67077</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[mvp]]></category>
            <dc:creator><![CDATA[Alberto Ballano]]></dc:creator>
            <pubDate>Wed, 19 Apr 2017 09:34:58 GMT</pubDate>
            <atom:updated>2017-08-18T12:17:01.274Z</atom:updated>
            <content:encoded><![CDATA[<p>Working on a messenger app is great, it&#39;s both complicated and fun. It sometimes requires you to try to figure it out how some giants in the market, like Whatsapp, Telegram or Facebook, dealt with some scenarios and challenges. At the same time you to still try to build a solution that fits your specific product.</p><p>In my last post I explained a <a href="https://tech.xing.com/reactive-views-retrying-errors-a59fffbd827f">reactive way of dealing with errors</a> and today I&#39;d like to share a specific, yet complex, feature: Incoming typing notifications.</p><p>The logic behind incoming typing notifications might sound pretty easy: <strong>While another user is typing, show it in the chat view</strong>. But turns out it&#39;s a bit more complicated. How do you know when the other user stopped typing? You might wait for the backend to tell you that. But that’s a waste of resources and also what happens if you lost the connection? What you need is a timeout. Take a look at this diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*3t8ty9mdlnYT3F2x18kdCw.png" /><figcaption>Simplified approach on how typing notifications works</figcaption></figure><p>Now let me break this down a bit: we will have 1 starting event and 2 stopping events.</p><ul><li>The starting event (blue) is another user typing. At that point the first thing we have to do is add this user to a list of typing users and then update our view to show that, why? Because many users could be typing at the same time, so we want to show different view states: <em>&quot;John is typing…&quot;</em>, <em>&quot;2 users are typing…&quot;</em>, etc.</li><li>One possible stopping event (orange) is whenever the typing user sends a message. At that point we know that he/she&#39;s no longer typing, so we can safely remove from the list and update the view again. In case that user start typing again we will receive a typing event (blue) and start from the beginning.</li><li>The other possible stopping event (purple) is the mentioned timeout: a safeguard in case that we loose the connection. Basically we&#39;re gonna have a timeout of about 5 seconds and, after that, if we didn&#39;t received any new typing events from that user, we will assume that he/she stopped typing.</li></ul><p>I&#39;ll admit I was heavily influenced by <a href="https://twitter.com/pacoworks">Pacoworks</a> and <a href="http://www.pacoworks.com/2017/03/11/about-memory-management-in-fully-reactive-apps-at-droidcon-bytes-february-17/">his talk about memory management in fully reactive apps</a>, so for this approach I wanted to play a bit with functional programming and specially with pure(ish) functions. That way I could remove a global state from the presenter, so everything is encapsulated inside the Rx chain. Because of that there is a single entry point to the Presenter, which is omitted here. That entry point calls this method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d7b99f3d1448c574fb1bb46d75367a5/href">https://medium.com/media/1d7b99f3d1448c574fb1bb46d75367a5/href</a></iframe><blockquote>Note: For simplicity I removed the entry point from the code. There I basically create the State and return a Disposable to the view, so the signature looks like:</blockquote><blockquote>public static Disposable initialize(Configuration config)</blockquote><p>There are several things to mention here:</p><ul><li>The function is static, that means that it only deals with the given inputs and doesn&#39;t modify any global state.</li><li>We&#39;re given a Configuration and a State. The Configuration is a wrapper around our dependencies, something similar to a <a href="https://medium.com/@JorgeCastilloPr/kotlin-dependency-injection-with-the-reader-monad-7d52f94a482e">Reader monad</a> but worse. The State is nothing more than that: it contains our current typing users list.</li><li>Although our State and Configuration are immutable, there&#39;s one single thing that is not! Did you see it? Exactly, is the currentlyTypingUser because we need to hold the count of typing users and, therefore, we need to add and remove elements from it.</li><li>Although the function returns a Completable it will keep listening for incoming notifications even if the Completable in flatMapCompletable completes, why? Because flatMapCompletable completes when both the upstream and the given Completable terminates, but our Observable never does that by default.</li></ul><p>OK, this basically covers the entry point I showed before, let&#39;s continue with the scheduling:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee15fdf081ae8889d3b3a312f8e73e95/href">https://medium.com/media/ee15fdf081ae8889d3b3a312f8e73e95/href</a></iframe><p>This basically covers our stop event by doing an amb (takes the first terminate event) of our 2 stopping events, so we remove the specific typing user and update the view again. Let&#39;s take a look at the timeout now:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/305a5c44387ed70c8d315be85884ccc8/href">https://medium.com/media/305a5c44387ed70c8d315be85884ccc8/href</a></iframe><p>What we have here is basically an initial event plus a subscription to the next typing events of the same user (note that I simplified that part in the filter). Now we switchMap to a <strong>timer.</strong> This means that we start the timer with the initial event and <strong>it will be reset</strong> every time we receive an additional typing event (note that this will be done here and not in our initial setup method). After that we take the first value and return a Completable.</p><p>Since our notificationManager provides a never-ending Observable but we&#39;re only interested on getting the first timeout, we just take(1) to make it complete and ignore the emission.</p><p>Let&#39;s see the final piece of the puzzle:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a594e8ad00f9192ad78dc57784e53fad/href">https://medium.com/media/a594e8ad00f9192ad78dc57784e53fad/href</a></iframe><p>Really simple, right? Listen for new messages of this specific user and do the same completable-trick™.</p><h4>Summary</h4><p>With this we covered mostly all of our initial diagram, right? But what happens with that green and red actions in it? The trick with them is that they&#39;re modifying a state and then updating the view, so there are chances of having a race condition!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*FXV0FJf1IgH64FqU0jF6fA.gif" /><figcaption>Any dev dealing with race conditions</figcaption></figure><p>Fortunately for us this 2 sections of our code will be executed in the main thread, so the entire block should be thread safe. But is good to have them identified in case that changes at some point.</p><h4>Bonus point: Tests</h4><p>A bonus point of this approach is in the tests: basically this class is tested through a single-static entry point, meaning that we give inputs and we test &quot;outputs&quot;, in this case being our outputs interactions with the view of this form:</p><pre><em>verify</em>(view).updateOneParticipantTyping()</pre><p>And that&#39;s it, there&#39;s no need of testing any state, which allows us to change mostly everything inside the class without touching a single test.</p><p>That was it, I hope you liked the post and if you did please hit the recommend button below and subscribe for future posts!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15a514b67077" width="1" height="1" alt=""><hr><p><a href="https://tech.new-work.se/reactive-functional-presenters-handling-typing-notifications-15a514b67077">Reactive Functional Presenters: Handling Typing notifications.</a> was originally published in <a href="https://tech.new-work.se/">New Work Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Functors, Applicatives, And Monads in Pictures. Part 3/3]]></title>
            <link>https://medium.com/hackernoon/kotlin-functors-applicatives-and-monads-in-pictures-part-3-3-832d58d92445?source=rss-14e6209c1c05------2</link>
            <guid isPermaLink="false">https://medium.com/p/832d58d92445</guid>
            <category><![CDATA[applicative]]></category>
            <category><![CDATA[functor]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[monads]]></category>
            <dc:creator><![CDATA[Alberto Ballano]]></dc:creator>
            <pubDate>Tue, 11 Apr 2017 11:01:01 GMT</pubDate>
            <atom:updated>2019-04-25T09:30:56.463Z</atom:updated>
            <content:encoded><![CDATA[<p>First of all, if you didn’t read the previous posts, go do so, otherwise you might be missing some essential concepts!</p><ul><li><a href="https://hackernoon.com/kotlin-functors-applicatives-and-monads-in-pictures-part-1-3-c47a1b1ce251">Kotlin Functors, Applicatives, And Monads in Pictures. Part 1/3</a></li><li><a href="https://hackernoon.com/kotlin-functors-applicatives-and-monads-in-pictures-part-2-3-f99a09efd1ec">Kotlin Functors, Applicatives, And Monads in Pictures. Part 2/3</a></li></ul><h3>Monads</h3><p>How to learn about Monads:</p><ol><li>Get a PhD in computer science.</li><li>Throw it away because you don’t need it for this section!</li></ol><p>Monads add a new twist.</p><p><a href="https://hackernoon.com/tagged/functors">Functors</a> apply a function to a wrapped value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/0*Ify-0OWj6YL7Biyp.png" /></figure><p>Applicatives apply a wrapped function to a wrapped value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/0*FNa0IqM3n016ufYh.png" /></figure><p>Monads apply a function that returns a wrapped value to a wrapped value. Monads have a function flatMap (liftM or &gt;&gt;= in Haskell) to do this.</p><pre>inline fun &lt;B&gt; flatMap(f: (A) -&gt; Option&lt;B&gt;): Option&lt;B&gt; = <br>when (this) {<br>    is None -&gt; this<br>    is Some -&gt; f(value)<br>}</pre><p>Let’s see an example. Good ol’ Option is a monad:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/0*kdpByXzPXXNgJ4v8.png" /></figure><p>Just a monad hanging out.</p><p>Suppose half is a function that only works on even numbers:</p><pre>fun half(a: Int) = when {<br>    a % 2 == 0 -&gt; Some(a / 2)<br>    else -&gt; None<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/0*bM7sbALwfuSmwoj7.png" /></figure><p>What if we feed it a wrapped value?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/176/0*I66ezQb2qu243RLh.png" /></figure><p>We need to use flatMap (&gt;&gt;= in Haskell) to shove our wrapped value into the function. Here’s a photo of flatMap:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/0*MSDfsNNSfXqkXVYa.jpg" /></figure><p>Here’s how it works:</p><pre>Some(3).flatMap(::half)<br>// None<br>Some(4).flatMap(::half)<br>// Some(2)<br>None.flatMap(::half)<br>// None</pre><p>What’s happening inside? Let’s look at flatMap&#39;s (&gt;&gt;= in Haskell) signature again:</p><pre>// For Option<br>inline fun &lt;B&gt; flatMap(f: (A) -&gt; Option&lt;B&gt;): Option&lt;B&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/0*G8_Zuhcn94-9OR0Z.png" /></figure><p>So Option is a Monad. Here it is in action with a Some(3)!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/0*yWziebMi8kBhH4Sn.png" /></figure><p>And if you pass in a None it’s even simpler:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/0*bJFoxQ-Ylp2SIQg2.png" /></figure><p>You can also chain these calls (by using an infix version of flatMap):</p><pre>Some(20) flatMap ::half flatMap ::half flatMap ::half<br>// =&gt; None</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/0*N-dZjxCsHwnK_KlT.png" /></figure><blockquote><em>Note: the original article now describes Haskell’s </em><em>IO Monad. </em><a href="https://hackernoon.com/tagged/kotlin"><em>Kotlin</em></a><em> doesn&#39;t have anything like that so this translation skips it.</em></blockquote><h3>Conclusion</h3><ol><li>A functor is a type that implements map.</li><li>An applicative is a type that implements apply.</li><li>A monad is a type that implements flatMap.</li><li>Option implements map and flatMap, plus we can extend it to implement apply, so it is a functor, an applicative, and a monad.</li></ol><p>What is the difference between the three?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*eElNlhORdSeUxp6D.png" /></figure><ul><li><strong>functors</strong>: you apply a function to a wrapped value using map.</li><li><strong>applicatives</strong>: you apply a wrapped function to a wrapped value using apply.</li><li><strong>monads</strong>: you apply a function that returns a wrapped value, to a wrapped value using flatMap.</li></ul><p>So, dear friend (I think we are friends by this point), I think we both agree that monads are easy and a SMART IDEA(tm). Now that you’ve wet your whistle on this guide, why not pull a Mel Gibson and grab the whole bottle. Check out LYAH’s <a href="http://learnyouahaskell.com/a-fistful-of-monads">section on Monads</a>. There’s a lot of things I’ve glossed over because Miran does a great job going in-depth with this stuff.</p><blockquote><em>Thanks for reading through this article series, if you have any feedback, suggestion, or error to report please tweet me </em><a href="http://twitter.com/aballano"><em>@aballano</em></a><em>, or leave a comment below.</em></blockquote><blockquote><em>If you want to play around with the code head over to GitHub and </em><a href="https://github.com/aballano/FAM-Playground"><em>clone the Playground</em></a></blockquote><blockquote><em>Once again, thanks </em><a href="https://twitter.com/_egonschiele"><em>Adit</em></a><em> for the wonderful post, and for all the other great ones on </em><a href="http://adit.io/index.html"><em>the blog</em></a><em>.</em></blockquote><p>Happy Koding!</p><figure><a href="http://bit.ly/HackernoonFB"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hqOaABQ7XGPT-OYNgiUBg.png" /></a></figure><figure><a href="https://goo.gl/k7XYbx"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vgw1jkA6hgnvwzTsfMlnpg.png" /></a></figure><figure><a href="https://goo.gl/4ofytp"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gKBpq1ruUi0FVK2UM_I4tQ.png" /></a></figure><blockquote><a href="http://bit.ly/Hackernoon">Hacker Noon</a> is how hackers start their afternoons. We’re a part of the <a href="http://bit.ly/atAMIatAMI">@AMI</a> family. We are now <a href="http://bit.ly/hackernoonsubmission">accepting submissions</a> and happy to <a href="/service/mailto:partners@amipublications.com">discuss advertising &amp; sponsorship</a> opportunities.</blockquote><blockquote>If you enjoyed this story, we recommend reading our <a href="http://bit.ly/hackernoonlatestt">latest tech stories</a> and <a href="https://hackernoon.com/trending">trending tech stories</a>. Until next time, don’t take the realities of the world for granted!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*35tCjoPcvq6LbB3I6Wegqw.jpeg" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=832d58d92445" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/kotlin-functors-applicatives-and-monads-in-pictures-part-3-3-832d58d92445">Kotlin Functors, Applicatives, And Monads in Pictures. Part 3/3</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Functors, Applicatives, And Monads in Pictures. Part 2/3]]></title>
            <link>https://medium.com/hackernoon/kotlin-functors-applicatives-and-monads-in-pictures-part-2-3-f99a09efd1ec?source=rss-14e6209c1c05------2</link>
            <guid isPermaLink="false">https://medium.com/p/f99a09efd1ec</guid>
            <category><![CDATA[applicative]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[monads]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[functor]]></category>
            <dc:creator><![CDATA[Alberto Ballano]]></dc:creator>
            <pubDate>Tue, 04 Apr 2017 11:02:01 GMT</pubDate>
            <atom:updated>2019-04-25T09:34:16.957Z</atom:updated>
            <content:encoded><![CDATA[<p>First of all, if you didn&#39;t read the previous post, go do so, otherwise you might be missing some essential concepts!</p><p><a href="https://medium.com/@aballano/kotlin-functors-applicatives-and-monads-in-pictures-part-1-3-c47a1b1ce251">Kotlin Functors, Applicatives, And Monads in Pictures. Part 1/3</a></p><h3>Applicatives</h3><p>Applicatives take it to the next level. With an applicative, our values are wrapped in a context, just like <a href="https://hackernoon.com/tagged/functors">Functors</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/0*tLlU2WEqCu7jYUSj.png" /></figure><p>But our functions are wrapped in a context too!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/135/0*-3EM_WBCQu5KlCUX.png" /></figure><p>Yeah. Let that sink in. Applicatives don’t kid around. Unlike Haskell, <a href="https://hackernoon.com/tagged/kotlin">Kotlin</a> doesn’t have <em>yet</em> a built-in way to deal with Applicatives. But it is very easy to add one! We can define an apply function for every type supporting Applicative, which knows how to apply a function wrapped in the context of the type to a value wrapped in the same context:</p><pre>infix fun &lt;A, B&gt; Option&lt;(A) -&gt; B&gt;.apply(f: Option&lt;A&gt;): Option&lt;B&gt; =<br>        when (this) {<br>            is Option.None -&gt; Option.None<br>            is Option.Some -&gt; f.map(this.value)<br>        }</pre><pre>infix inline fun &lt;A, reified B&gt; Array&lt;(A) -&gt; B&gt;.apply(a: Array&lt;A&gt;) =<br>        Array(this.size * a.size) {<br>            this[it / a.size](a[it % a.size])<br>        }</pre><p>If both this and the function are Some, then the function is applied to the unwrapped option, otherwise None is returned.</p><p>For the Array I&#39;m using its constructor parameters to generate the array, although note that this wouldn&#39;t be the most performant choice for bigger arrays.</p><blockquote><strong>Note:</strong> this would be the&lt;*&gt; in Haskell, so again we could use a * operator if needed.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/0*YZDbwqs5Vxy-ldbA.png" /></figure><p>i.e:</p><pre>Some({ a: Int -&gt; a + 3 }) apply Some(2)<br>// =&gt; Some(5)</pre><p>If you look carefully you will see that our operator only works in this specific order: Option(function) apply Option(value) why? Because our extension function is defined in that order. Then, couldn’t I just make another extension function to work the other way around, like:</p><pre>fun &lt;A, B&gt; Option&lt;A&gt;.apply(o: Option&lt;(A) -&gt; B&gt;) = {...}<br>fun &lt;A, B&gt; Option&lt;(A) -&gt; B&gt;.apply(o: Option&lt;A&gt;) = {...}</pre><p>Technically not. Since Kotlin produces same code as Java would, it has to deal with our friend the <a href="https://docs.oracle.com/javase/tutorial/java/generics/erasure.html">type erasure</a>. So basically those 2 functions would loose the generic types at compile time (and become just Option), making them equal and therefore invalid. But here’s a trick, we could use a so called dummyImplicit (and you can read why <a href="http://stackoverflow.com/questions/34745066/dummyimplicits-is-this-used-and-how/34746255?stw=2#34746255">here</a>) so it would look like:</p><pre>fun &lt;A, B&gt; Option&lt;A&gt;.apply(f: Option&lt;(A) -&gt; B&gt;, <br>                           dummyImplicit: Any? = null): Option&lt;B&gt; = <br>when (this) {<br>    is Option.None -&gt; Option.None<br>    is Option.Some -&gt; f.map { it(value) }<strong><br></strong>}</pre><p>This allows us to do:</p><pre>Some(2).<em>apply</em>(Some(<strong>{ </strong>a: Int <strong>-&gt; </strong>a + 3 <strong>}</strong>))<br>// =&gt; Some(5)</pre><p>But unfortunately it makes the infix impossible since infix functions only have one parameter :(</p><p>So, following our previous explanation, using <em>apply </em>can lead to some interesting situations. For example:</p><pre>arrayOf&lt;(Int) -&gt; Int&gt;({ it + 3 }, { it * 2 }) <em>apply </em>arrayOf(1, 2, 3)<br>// =&gt; [ 4, 5, 6, 2, 4, 6 ]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/0*dTv-_gpKc-DbXIx7.png" /></figure><blockquote><strong><em>Note:</em></strong><em> the original article now shows how Applicatives are more powerful than Functors in that they allow function application with multiple parameters. Again this is not feasible in vanilla Kotlin, but we can work around it by defining the function we want to handle in a </em><a href="https://en.wikipedia.org/wiki/Currying"><em>curried way</em></a><em>.</em></blockquote><p>Here’s something you can do with Applicatives that you can’t do with Functors. How do you apply a function that takes two arguments to two wrapped values?</p><pre>fun curriedAddition(a: Int) = { b: Int -&gt;<br>    a + b<br>}</pre><pre>Some(3) map ::curriedAddition map Some(2)<br>// =&gt; COMPILER ERROR</pre><p>Applicatives:</p><pre>Some(3) map ::curriedAddition apply Some(2)<br>// =&gt; Some(5)</pre><p>Wait, what?? Let me break it down step by step:</p><pre>Some(3) map ::curriedAddition<br>// =&gt; Some({ 3 + b })</pre><pre>Some({ 3 + b }) apply Some(2)<br>// =&gt; Some(5)</pre><p>Applicative pushes Functor aside. “Big boys can use functions with any number of arguments,” it says. “Armed with map and apply, I can take any function that expects any number of unwrapped values. Then I pass it all wrapped values, and I get a wrapped value out! AHAHAHAHAH!”</p><pre>fun curriedTimes(a: Int) = <strong>{ </strong>b: Int <strong>-&gt;<br>    </strong>a * b<br><strong>}</strong></pre><pre>Some(3) map ::curriedTimes apply Some(5)<br>// =&gt; Some(15)</pre><p>But wait, what if we want to go deeper?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*cmUv1wycDkmX3CQWYBRm2g.png" /></figure><p>Suppose we have a triple product function:</p><pre>fun tripleProduct(a: Int, b: Int, c: Int) = a * b * c</pre><p>We want to do the same as before but we don&#39;t want to manually curry it, so we have a curry function, in this case for 3 params:</p><pre>fun &lt;A, B, C, D&gt; curry(f: (A, B, C) -&gt; D): (A) -&gt; (B) -&gt; (C) -&gt; D = <strong>{ </strong>a <strong>-&gt; { </strong>b <strong>-&gt; { </strong>c <strong>-&gt; </strong>f(a, b, c) <strong>} } }</strong></pre><blockquote>Thanks <a href="https://medium.com/u/e856388adc0e">Ľuboš Mudrák</a> for the suggestion!</blockquote><p>Well, that&#39;s easy:</p><pre>Some(3) map <em>curry</em>(::tripleProduct) apply Some(5) apply Some(4)<br>// =&gt; Some(60)</pre><h4>That’s it! Hope you enjoyed this second part as much as I did while writting it, remember that you can find all the code in the <a href="https://github.com/aballano/FAM-Playground">playground repo I created</a> and hope to see you in the next and final series!</h4><p>The third and final part is already available&quot;</p><p><a href="https://medium.com/@aballano/kotlin-functors-applicatives-and-monads-in-pictures-part-3-3-832d58d92445">Kotlin Functors, Applicatives, And Monads in Pictures. Part 3/3</a></p><figure><a href="http://bit.ly/HackernoonFB"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hqOaABQ7XGPT-OYNgiUBg.png" /></a></figure><figure><a href="https://goo.gl/k7XYbx"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vgw1jkA6hgnvwzTsfMlnpg.png" /></a></figure><figure><a href="https://goo.gl/4ofytp"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gKBpq1ruUi0FVK2UM_I4tQ.png" /></a></figure><blockquote><a href="http://bit.ly/Hackernoon">Hacker Noon</a> is how hackers start their afternoons. We’re a part of the <a href="http://bit.ly/atAMIatAMI">@AMI</a> family. We are now <a href="http://bit.ly/hackernoonsubmission">accepting submissions</a> and happy to <a href="/service/mailto:partners@amipublications.com">discuss advertising &amp; sponsorship</a> opportunities.</blockquote><blockquote>If you enjoyed this story, we recommend reading our <a href="http://bit.ly/hackernoonlatestt">latest tech stories</a> and <a href="https://hackernoon.com/trending">trending tech stories</a>. Until next time, don’t take the realities of the world for granted!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*35tCjoPcvq6LbB3I6Wegqw.jpeg" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f99a09efd1ec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/kotlin-functors-applicatives-and-monads-in-pictures-part-2-3-f99a09efd1ec">Kotlin Functors, Applicatives, And Monads in Pictures. Part 2/3</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Functors, Applicatives, And Monads in Pictures. Part 1/3]]></title>
            <link>https://medium.com/hackernoon/kotlin-functors-applicatives-and-monads-in-pictures-part-1-3-c47a1b1ce251?source=rss-14e6209c1c05------2</link>
            <guid isPermaLink="false">https://medium.com/p/c47a1b1ce251</guid>
            <category><![CDATA[monads]]></category>
            <category><![CDATA[applicative]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[functor]]></category>
            <dc:creator><![CDATA[Alberto Ballano]]></dc:creator>
            <pubDate>Tue, 28 Mar 2017 10:54:25 GMT</pubDate>
            <atom:updated>2019-04-25T09:33:31.075Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>This is a translation of </em><a href="http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html"><em>Functors, Applicatives, And Monads In Pictures</em></a><em> from </em><a href="https://www.haskell.org/"><em>Haskell</em></a><em> into </em><a href="https://hackernoon.com/tagged/kotlin"><em>Kotlin</em></a><em>.</em></blockquote><blockquote><em>Actually this is a translation of </em><a href="http://www.mokacoding.com/blog/functor-applicative-monads-in-pictures/"><em>another translation from Haskell to Swift</em></a><em>.</em></blockquote><blockquote><em>I read through the original post and I found it really interesting for learning new concepts of FP, so I decided to do an additional translation (having also some fun in the way).</em></blockquote><blockquote><em>I also wanted to see how far can Kotlin get compared to Swift :)</em></blockquote><blockquote><em>If you enjoy this post be sure to say thanks to the author of the original version: </em><a href="http://adit.io/index.html"><em>Aditya Bhargava</em></a><em>, </em><a href="https://twitter.com/_egonschiele"><em>@_egonschiele</em></a><em> on Twitter.</em></blockquote><p>Here’s a simple value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/89/0*cWvHYgZpw85fz_QW.png" /></figure><p>And we know how to apply a function to this value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/0*XphGzXumvbJTBycX.png" /></figure><p>Simple enough. Lets extend this by saying that any value can be in a context. For now you can think of a context as a box that you can put a value in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/0*7ZPc_kKNSlCqiRXR.png" /></figure><p>Now when you apply a function to this value, you’ll get different results <strong>depending on the context</strong>. This is the idea that Functors, Applicatives, Monads, Arrows etc are all based on. The Option data type defines two related contexts:</p><blockquote><strong><em>Note:</em></strong><em> the pictures use Maybe (Just | None) from Haskell, which correspond to a custom Kotlin’s </em>Option<em> (Some | None) implementation.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/0*1NCb7mGijOSflxhO.png" /></figure><pre>sealed class Option&lt;out A&gt; {<br>  object None : Option&lt;Nothing&gt;()<br>  data class Some&lt;out A&gt;(val value: A) : Option&lt;A&gt;()<br>}</pre><p>In a second we will see how function application is different when something is a Some(T)versus a None. First let’s talk about <a href="https://hackernoon.com/tagged/functors">Functors</a>!</p><h3>Functors</h3><p>When a value is wrapped in a context, you can’t apply a normal function to it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/0*M7c-lRRTz8pKWpN4.png" /></figure><p>This is where map comes in (fmap in Haskell). map is from the street, map is hip to contexts. map knows how to apply functions to values that are wrapped in a context. For example, suppose you want to apply a function that adds 3 to Some(2). Use map:</p><pre>fun sumThree(n: Int) = n + 3<br><br>Option.Some(2).map(::sumThree)<br>// =&gt; Some(5)</pre><p>or with a simple syntax using an anonymous lambda:</p><pre>Option.Some(2).map { it + 3 }<br>// =&gt; Some(5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/0*iAU0E7CdHqjfQ9RK.png" /></figure><p><strong>Bam!</strong> map shows us how it’s done! But how does map know how to apply the function?</p><h3>Just what is a Functor, really?</h3><p>A Functor is any type that defines how map (fmap in Haskell) applies to it. Here’s how mapworks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/0*egb47QB6zSr1jbl2.png" /></figure><p>So we can do this:</p><pre>Option.Some(2).map { it + 3 }<br>// =&gt; Some(5)</pre><p>And map magically applies this function, because Option is a Functor. It specifies how map applies to Somes and Nones:</p><pre>inline fun &lt;B&gt; map(f: (A) -&gt; B): Option&lt;B&gt; = when (this) {<br>    is None -&gt; this<br>    is Some -&gt; Some(f(value))<br>}</pre><p>Here’s what is happening behind the scenes when we write Option.Some(2).map { it + 3 }:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/0*2ePtQNke8BGZT5MN.png" /></figure><p>So then you’re like, alright map, please apply { it + 3 } to a None?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/0*w6a1JBnkBrpKlW1N.png" /></figure><pre>Option.None.map { it + 3 }<br>// =&gt; None</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*HJUxTnL7aNTGmuG-.png" /></figure><p>Well, there&#39;s a gotcha here since the code above doesn&#39;t compile. Why? Well because in this case None doesn&#39;t have a proper type, so you cannot do a plus with type Nothing. But it should be fine because you normally won&#39;t write that code but something like:</p><pre>val option: Option&lt;Int&gt; = someCallThatMightReturnNone()<br>option.map { it + 3 }<br>// =&gt; None</pre><p>Like Morpheus in the Matrix, map knows just what to do; you start with None, and you end up with None! map is zen. Now it makes sense why the Option type exists. For example, here’s how you work with a database record in a language without Option:</p><pre>val post = Post.findByID(1)<br>return post?.title</pre><p>But in Kotlin using the Option functor:</p><pre>findPost(1).map(::getPostTitle)</pre><p>If findPost(1) returns a post, we will get the title with getPostTitle. If it returns None, we will return None!</p><p>We can even define map as an infix function for (&lt;$&gt; in Haskell), and do this instead:</p><pre>inline infix fun &lt;B&gt; map(f: (A) -&gt; B): Option&lt;B&gt; { ... }<br><br><em>findPost</em>(1) map ::getPostTitle</pre><blockquote><strong><em>Note:</em></strong><em> we have to use just </em><em>map because </em><em>&lt;$&gt; wouldn&#39;t compile. Another option would be to override a common operator like </em><em>/ or </em><em>*</em></blockquote><p>Here’s another example: what happens when you apply a function to an array?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/0*lcScORdRNawytDNN.png" /></figure><p>Arrays are functors too*!</p><p>*Basically Kotlin provides an extension function to all iterables in the form:</p><pre>inline fun &lt;T, R&gt; Iterable&lt;T&gt;.map(transform: (T) -&gt; R): List&lt;R&gt; {..}</pre><p>Okay, okay, one last example: what happens when you apply a function to another function?</p><pre>{ a: Int -&gt; a + 2 } map { a: Int -&gt; a + 3 }<br>// =&gt; ???</pre><p>Here&#39;s a function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/0*fT23UDVq18hzvatb.png" /></figure><p>Here’s a function applied to another function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/0*kKizWpvf5xsrDDaj.png" /></figure><p>The result is just another function!</p><pre>typealias IntFunction = (Int) -&gt; Int<br><br>infix fun IntFunction.map(g: IntFunction): IntFunction {<br>    return { x -&gt; this(g(x)) }<br>}<br><br>val foo = { a: Int -&gt; a + 2 } <em>map </em>{ a: Int -&gt; a + 3 }<strong><br></strong>foo(10)<br>// =&gt; 15</pre><p>So functions can be Functors too! When you use map on a function, you’re just doing function composition!</p><h4>Well, that&#39;s it for today, I hope you got the idea about what&#39;s a Functor. Since the original post was pretty long, I&#39;ll continue in the next series with Applicatives. Now go try write some Functors in Kotlin!</h4><h4>Wanna play around with the code? Take a look at <a href="https://github.com/aballano/FAM-Playground">https://github.com/aballano/FAM-Playground</a></h4><p>Want more? Go try applicatives in the second part!</p><p><a href="https://medium.com/@aballano/kotlin-functors-applicatives-and-monads-in-pictures-part-2-3-f99a09efd1ec">Kotlin Functors, Applicatives, And Monads in Pictures. Part 2/3</a></p><figure><a href="http://bit.ly/HackernoonFB"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hqOaABQ7XGPT-OYNgiUBg.png" /></a></figure><figure><a href="https://goo.gl/k7XYbx"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vgw1jkA6hgnvwzTsfMlnpg.png" /></a></figure><figure><a href="https://goo.gl/4ofytp"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gKBpq1ruUi0FVK2UM_I4tQ.png" /></a></figure><blockquote><a href="http://bit.ly/Hackernoon">Hacker Noon</a> is how hackers start their afternoons. We’re a part of the <a href="http://bit.ly/atAMIatAMI">@AMI</a> family. We are now <a href="http://bit.ly/hackernoonsubmission">accepting submissions</a> and happy to <a href="/service/mailto:partners@amipublications.com">discuss advertising &amp; sponsorship</a> opportunities.</blockquote><blockquote>If you enjoyed this story, we recommend reading our <a href="http://bit.ly/hackernoonlatestt">latest tech stories</a> and <a href="https://hackernoon.com/trending">trending tech stories</a>. Until next time, don’t take the realities of the world for granted!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*35tCjoPcvq6LbB3I6Wegqw.jpeg" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c47a1b1ce251" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/kotlin-functors-applicatives-and-monads-in-pictures-part-1-3-c47a1b1ce251">Kotlin Functors, Applicatives, And Monads in Pictures. Part 1/3</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 reasons to give at least one public talk in your life]]></title>
            <link>https://medium.com/@aballano/10-reasons-to-give-at-least-one-public-talk-in-your-life-52ea550ad7d0?source=rss-14e6209c1c05------2</link>
            <guid isPermaLink="false">https://medium.com/p/52ea550ad7d0</guid>
            <category><![CDATA[life-lessons]]></category>
            <category><![CDATA[public-speaking]]></category>
            <dc:creator><![CDATA[Alberto Ballano]]></dc:creator>
            <pubDate>Wed, 22 Mar 2017 14:54:49 GMT</pubDate>
            <atom:updated>2017-03-23T09:53:16.473Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2KVKcPSHEpJNCskgesmPlw.png" /><figcaption>Me at the <a href="https://flipper83.github.io/freakend-mobile/">Freakend</a> Mobile 2017</figcaption></figure><p>Recently I gave couple of <a href="https://speakerdeck.com/shyish">technical talks in few conferences</a> and I got a really enjoyable experience doing it. And although I’m no expert on public speaking I thought about sharing my amateur experience for those undecided to try it.</p><p>On the one hand, public speaking is one of those things that terrify people. On the other, day by day in the world, many people join conferences as speakers to talk about something new. They talk about a problem or different ways to approach solutions to it.</p><p>Are those people fearless of public speaking? Are they super smart or anything else? Most likely not, most of them are normal people that want to share something to the world.</p><p>What do they have in special to talk in conferences you ask? They dedicated enough time to research or they’re <strong>sharing an experience</strong>.</p><p>Does that mean that anybody can give a public talk? Depends on each person, but <strong>there are 2 ingredients</strong>:</p><ul><li><strong>Research or experience</strong>: Do you have a particular interest? Then you only need to dedicate enough time to research about it and show it to people. It will also be interesting for them. Or have you dealt a lot and solved problems about a topic? Then you might want to share your experience so others can learn from it.</li><li><strong>Courage</strong>: Public speaking could be scary. We all share the fear of not liking or making mistakes in front of other people. My key secret was seeing the audience as friends. It helped me calm down and speak at a normal, or even slower, pace. There are many guides on how to speak in YouTube (search for <a href="https://www.youtube.com/results?search_query=ted+talk+public+speaking">TED talks</a>).</li></ul><p>You might be asking yourself this question now: Why should I give a talk?</p><p>Well I’ll give you <strong>10 reasons</strong> to do so:</p><h3>#1: You will learn something</h3><p>If you want to give a good talk you have to research, and the chances of learning new things in the way are pretty high!</p><p>Even if you’re sharing your experience people will contact you to know more. Or they could have a different approach from which you can learn more from.</p><h3>#2: You will teach or even inspire others</h3><p>Sharing is caring, right? There are many ways of sharing knowledge, and giving a talk is one of them and a good one actually. Because let’s be honest: some people will read an article and forget about it. By giving a talk you speak, you show images, even sounds, and that last way longer in humans’ memory.</p><h3>#3: Is good for your social skills</h3><p>Public speaking improves your way of communicating in general. It makes you think what’s the best way of expressing your ideas. In the end, forces you to give better explanations of your mental processes. It also helped me out for being more open minded and understanding different points of view.</p><h3>#4: Networking</h3><p>Giving talks makes you, most times, go to conferences. People interested in what you presented will approach you, so it&#39;s easy for you and them to get in touch. And getting in touch with people allows you to grow your professional network.</p><h3>#5: Is a good addition to your CV</h3><p>I’ve done several job interviews as interviewer already. Interviewing someone that gave public talks makes me think that this person has courage and cares for other people. If the talk is related to the job, it shows that the person has passion and at least they know about the topic they talked about.</p><h3>#6: You might discover that you’re good at it</h3><p>Who knows? Maybe you enjoy it a lot, or you discover that you had a hidden talent for public speaking. Well, the only way of checking is trying!</p><h3>#7: Improves your self-confidence</h3><p>Some people, like myself, are quiet or shy at work or in our private life. Sometimes we think that our ideas are not good enough to be shared. Sometimes we think that we could look stupid by saying something that the rest of the world already know. Well, if that’s your case, as it was mine, you’re wrong!</p><p>People do share opinions, people like to hear other people’s opinions. People like to hear other people’s experiences. You might think that other people already know what you want to say but, are you sure? If you go to a conference or similar, do you think the people there know everything already? I don’t think so.</p><p>Considering that you’re on the average of knowledge for a topic, there will be people knowing more but also less. So there’s a big chance that your audience is there to learn more, so is worth trying.</p><p>Giving a public talk breaks that barrier that some of us have of expressing our ideas or opinions.</p><h3>#8: Improves your expressiveness</h3><p>You need to consider that you will have three kind of audiences: expert, average and newbie. For that reason is important to follow two simple rules when explaining a concept:</p><ul><li><strong>Be correct</strong>: Name the things with the appropriate name and use the right terminology. Otherwise the “expert” audience won’t totally understand you.</li><li><strong>Expressiveness</strong>: After explaining something in the correct way, you might want to give an example. An explanation with your own words helps the “newbie” audience to get the idea. And, even more, they will remember the correct terminology that you used.</li></ul><p>Applying these two rules allows you to discover and understand the proper terminology for what you’re talking about. By giving an explanation with your own words you can make sure that you understand what you’re talking about. It also encourages you to have these rules in mind for any other concept you want to explain, making you more professional.</p><p>The average people, on the other hand, will be grateful to have both approaches.</p><h3>#9: Develops your sales skills</h3><p>Sometimes you want to “sell” something, and by selling I mean promoting or presenting. It could be something you worked on, something your company has created or something you’re passionate about. In any case, giving a public talk will put you in a situation where you want to let the people know why this product/idea is better than any others. So it could lead you to think as a salesman/woman in some way.</p><h3>#10: It&#39;s good for your company</h3><p>Probably not the most important for everybody. When you’re representing your company you’re telling people: <em>“look, this is how/what we do at my company”.</em> Some of them might find it interesting or inspiring and they might follow your example. Some of them could even consider joining your company. The first advantage is that your company, as well as you, would get more visibility. The second is that it will become easier for your team to hire new talented people.</p><p>Of course all of the above doesn&#39;t mean that you only get those skills by doing public talks, but hey, it really helps!</p><p>And you? When are you giving your first talk?</p><p><em>Thanks a lot to </em><a href="https://twitter.com/patriciabendala"><em>Patricia</em></a><em>, </em><a href="https://medium.com/@florina.muntenescu"><em>Florina</em></a><em>, </em><a href="https://medium.com/@raul.h82"><em>Raul</em></a><em>, </em><a href="https://medium.com/@a.ligataj"><em>Ana</em></a><em> and </em><a href="https://twitter.com/pacoworks"><em>Paco</em></a><em> for the support and reviews!!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52ea550ad7d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reactive Views: retrying errors]]></title>
            <link>https://tech.new-work.se/reactive-views-retrying-errors-a59fffbd827f?source=rss-14e6209c1c05------2</link>
            <guid isPermaLink="false">https://medium.com/p/a59fffbd827f</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mvp]]></category>
            <category><![CDATA[rxjava]]></category>
            <dc:creator><![CDATA[Alberto Ballano]]></dc:creator>
            <pubDate>Wed, 09 Nov 2016 08:43:11 GMT</pubDate>
            <atom:updated>2017-02-02T01:26:37.766Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>This post was featured in </strong><a href="http://androidweekly.net/issues/issue-231"><strong>Android Weekly’s #231 issue</strong></a><strong>.</strong></blockquote><p>After having a good adoption of RxJava and clean architecture in our XING Android app codebase we’ve been lately considering about iterating more over our already implemented <a href="http://martinfowler.com/eaaDev/PassiveScreen.html">passive view</a> concept in MVP, as a result we found couple of interesting articles about Reactive Views, specially <a href="https://artemzin.com/blog/rxui-talking-to-android-view-layer-in-a-reactive-way">this one</a> from <a href="https://medium.com/u/4600c10f9c5a">Artem Zinnatullin</a>, which illuminated our way to go for following improvements to the pattern in our app.</p><p>As Artem mentions in his article, RxBinding works really well with this Reactive Views approach, even though some UI components don’t have their binding in the library, implementing them manually by just looking at the source code of others is pretty straightforward.</p><h3>The feature</h3><p>We had to implement a simple feature in our <a href="https://blog.xing.com/de/2016/10/19/schneller-und-uebersichtlicher-runderneuerte-nachrichtenfunktion-bei-xing/">Messenger app</a>: when the user long clicks on a chat we have to show a dialog to confirm its deletion.</p><h4>View Binding</h4><p>So, since our view is currently almost 100% passive our initial approach was to expose an Observable bound to the RecyclerView’s item long click and get it from the presenter, but unfortunately RxBinding doesn’t (<a href="https://github.com/JakeWharton/RxBinding/pull/115#issuecomment-136941173">and won’t</a>) contain any binds for this approach, so we decided to <a href="https://gist.github.com/Shyish/92257b6348312b541aa4f6b205eb14e4">write our own</a>.</p><p>The usage is pretty simple by using the same syntax as RxBinding:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f82c3f100e22dbcad1dc9865cb9492b/href">https://medium.com/media/3f82c3f100e22dbcad1dc9865cb9492b/href</a></iframe><p>Ok so now that we can easily forward each of our RecyclerView’s item long clicks to an Observable, let’s see the implementation in the View:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c1a9739c4a87f4547a09e775a48e3e8/href">https://medium.com/media/0c1a9739c4a87f4547a09e775a48e3e8/href</a></iframe><h4>Presenter action</h4><p>The presenter will then be bound to this observable in it’s initialization. Any long press will cause the chain to trigger making the Presenter aware of the event so it tells the View to show the dialog.</p><p>If the user confirms the deletion the View will then inform* the presenter by calling onDeleteChat and this one will make the network request:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed3dedb714cd1bec305ee60cba006718/href">https://medium.com/media/ed3dedb714cd1bec305ee60cba006718/href</a></iframe><blockquote>*Note that here we are breaking our Rx chain since the Dialog we’re using in our app doesn’t allow, for now, to be bound with Observables, but for normal cases that shouldn’t be a problem.</blockquote><h3>The error case</h3><p>But what happens if this request fails? We need to let the user know about this issue and even let him retry the operation, so what we wanted to do is to show a Snackbar with a “retry” action on it as shown in the <a href="https://material.google.com/patterns/errors.html#errors-app-errors">Material Design specification</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*chBtiRlnd3GU-kn0JJSvlg.png" /></figure><p>Since we’re working with Observables, would be really nice to use the <a href="http://reactivex.io/documentation/operators/retry.html">retryWhen</a> operator so we don’t have to worry about manually retrying anymore.</p><h4>View binding</h4><p>But, in order to achieve this, we first need to “Rxify ” our Snackbar as we did with the RecyclerView’s item long click, and since, again, RxBindings doesn’t have (<a href="https://github.com/JakeWharton/RxBinding/pull/302">yet</a>) a binding for it, we need to create one ourselves, so <a href="https://gist.github.com/Shyish/8af4cd774320c57ced0ec21f8840797e">that we did</a>.</p><p>Again, nothing really complicated, right? So now we again exposed a method in the view for this like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8195f0c856911c8b573848639d2ea8ba/href">https://medium.com/media/8195f0c856911c8b573848639d2ea8ba/href</a></iframe><h4>Presenter action</h4><p>So now we temporarily implemented the retryWhen incorrectly in our presenter and thus the code should be modified to look this way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fba40675b381272475a4492c1f597eb6/href">https://medium.com/media/fba40675b381272475a4492c1f597eb6/href</a></iframe><p>But as I said, this is wrong! Why? Because that’s not how retryWhen works!</p><p>The problem is that we were using a Completable since our API policy in this case is to make the request and either succeed or fail, we don’t expect response, and, in my opinion, <a href="https://github.com/ReactiveX/RxJava/issues/4809">the javadoc is not clear enough</a> (<a href="https://github.com/ReactiveX/RxJava/pull/4810">but is fixed in RxJava 2</a>) about what you have to do with the given Observable:</p><blockquote>Returns a Completable which given a Publisher and when this Completable emits an error, delivers that error through an Observable and the Publisher should return a value indicating a retry in response or a terminal event indicating a termination.</blockquote><p>After struggling with our tests not passing, we found <a href="http://blog.danlew.net/2016/01/25/rxjavas-repeatwhen-and-retrywhen-explained/">this great post by Dan Lew</a> with some nice clarifications plus a bonus point on the exact same problem:</p><blockquote><strong>The output </strong><strong>Observable has to use the input </strong><strong>Observable as its source.</strong> You must <em>react</em> to the Observable&lt;Throwable&gt; and emit based on it; you can&#39;t just return a generic stream.</blockquote><p>So, here’s the fixed code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c8d2611dd210ff32aa04c89a6e45ff2/href">https://medium.com/media/6c8d2611dd210ff32aa04c89a6e45ff2/href</a></iframe><h4>Summary</h4><p>That’s it! We made our view totally passive by just following the “orders” of the Presenter and by exposing observables from the user input, that way we make a full reactive chain which is really easy to test with the minimum effort, apart from creating our own Rx bindings :P which shouldn’t be the normal case anyway.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a59fffbd827f" width="1" height="1" alt=""><hr><p><a href="https://tech.new-work.se/reactive-views-retrying-errors-a59fffbd827f">Reactive Views: retrying errors</a> was originally published in <a href="https://tech.new-work.se/">New Work Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Studio tricks: Extra Inspections]]></title>
            <link>https://medium.com/@aballano/android-studio-tricks-extra-inspections-5f35c6901363?source=rss-14e6209c1c05------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f35c6901363</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[android-studio]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Alberto Ballano]]></dc:creator>
            <pubDate>Tue, 17 May 2016 17:46:02 GMT</pubDate>
            <atom:updated>2016-05-17T18:01:32.956Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*sjA0CkLN716CRfenyC2e7g.png" /></figure><p>When using Android Studio for development all of us have already encounter that the IDE shows some warnings on some specific actions we try to perform on the code, that is the Inspect code function and together with Lint helps developers to ship better and less buggy code.</p><p>But what happens if the provided Inspections are not enough for us? What if I want to be more strict with the code that is written in my app? Then you might encounter yourself having to read through hundred of Inspections in order to find some good ones. In this article I&#39;d like to recommend some useful inspections.</p><p>Let&#39;s get started:</p><h3>Some useful Inspections</h3><p>First of all, go to Android Studio &gt; Preferences &gt; Search for Inspections. I&#39;ll go group by group listing all the inspections I <strong>personally</strong> find useful, please refer to the description provided in AS for further explanation:</p><h4>Android &gt; Lint &gt; Correctness</h4><ul><li>Newer Library Versions Available</li></ul><h4>In Java:</h4><h4>Abstraction issues</h4><ul><li>Magic Number</li></ul><h4>Java &gt; Assignment Issues</h4><ul><li>Assignment used as condition</li></ul><h4>Java &gt; Class metrics</h4><ul><li>Inner class too deeply nested (nesting limit = 2)</li></ul><h4>Class structure</h4><ul><li>Abstract class may be interface</li><li>Multiple top level classes in single file</li><li>Non-&#39;final&#39; field in enum</li><li>Utility class not &#39;final&#39;</li><li>Utility class without private constructor</li></ul><h4>Code maturity issues</h4><ul><li>Call to &#39;printStackTrace()&#39; (disable for tests)</li><li>Use of System.out or System.err</li></ul><h4>Code style issues</h4><ul><li>Call to &#39;String.concat()&#39; can be replaced with &#39;+&#39;</li><li>&#39;equals()&#39; called on Enum value</li><li>&#39;expression.equals(&quot;literal&quot;)&#39; rather than &#39;“literal”.equals(expression)&#39;</li><li>Field may be &#39;final&#39;</li><li>&#39;indexOf()&#39; expression is replaceable with &#39;contains()&#39;</li><li>Redundant interface declaration</li><li>Redundant no-arg constructor</li><li>&#39;size() == 0&#39; replaceable with &#39;isEmpty()&#39;</li></ul><h4>Control flow issues</h4><ul><li>Conditional expression with identical branches</li><li>Unnecessary &#39;null&#39; check before &#39;instanceOf&#39; expression</li></ul><h4>Inheritance issues</h4><ul><li>Missing @Override annotation</li></ul><h4>Initialization issues</h4><ul><li>Double brace initialization</li></ul><h4>J2ME issues</h4><ul><li><strong>Array.length in loop condition</strong></li><li>Field repeatedly accessed in method</li><li><strong>Private member access between outer and inner classes</strong></li></ul><h4>Java language level migration aids</h4><ul><li>[Uncheck] &#39;for&#39; loop replaceable with &#39;foreach&#39;</li><li>[Uncheck] ‘while’ loop replaceable with ‘foreach’</li></ul><p>Why? See <a href="https://www.youtube.com/watch?v=MZOf3pOAM6A">this video</a> and/or read <a href="https://medium.com/google-developers/developing-for-android-ii-bb9a51f8c8b9">this article</a>.</p><h4>JavaBeans issues</h4><ul><li>Suspicius getter/setter</li></ul><h4>Memory issues</h4><ul><li>Inner class may be &#39;static&#39;</li><li>Zero-length array allocation</li></ul><h4>Performance issues</h4><ul><li>Call to simple getter from within class</li><li>Call to simple setter from within class</li><li>Dynamic regular expression could be replaced by compiled Pattern</li><li>&#39;equals()&#39; or &#39;hashCode()&#39; called on java.net.URL object</li><li>Field may be &#39;static&#39;</li><li>Map replaceable with EnumMap</li><li>Method may be &#39;static&#39;</li><li>Set replaceable with EnumSet</li><li>Single character string concatenation</li><li>&#39;String.equals(&quot;&quot;)&#39;</li></ul><h4>Probable bugs</h4><ul><li>Array comparison using &#39;==&#39; instead of &#39;Arrays.equals()&#39;</li><li>Cast conflicts with &#39;instanceOf&#39;</li><li>Comparable implemented but &#39;equals()&#39; not implemented</li><li><strong>Constant conditions &amp; exceptions (very nice to use with @Nullable and @NonNull annotations)</strong></li></ul><p>There are many more that could be useful for you/your team, so I really encourage you to take a look at the available ones and <a href="https://medium.com/sebs-top-tips/share-the-settings-with-the-whole-team-android-studio-protip-6-3cce16eb2ea4#.50wih1rzb">add them to your local repo so everybody gets the same warnings</a>.</p><p>[Update] As <a href="https://medium.com/u/2f8c1dc6e52d">Saúl Molinero</a> mentioned in the comments “typing ‘cmd + shift + a’ + ‘run inspection by name’ allows you to run a single inspection without need to run a profile filled with a set of inspections.”</p><p>Do you have any favourite inspection? Please share in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f35c6901363" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>