<?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 Krupal Shah on Medium]]></title>
        <description><![CDATA[Stories by Krupal Shah on Medium]]></description>
        <link>https://medium.com/@krupalshah55?source=rss-54331e40d213------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wuphgFDjWrc6ZIMlNB34aA.jpeg</url>
            <title>Stories by Krupal Shah on Medium</title>
            <link>https://medium.com/@krupalshah55?source=rss-54331e40d213------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 13:16:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@krupalshah55/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[Refactoring utility classes with Kotlin : Shared Preferences]]></title>
            <link>https://medium.com/@krupalshah55/manipulating-shared-prefs-with-kotlin-just-two-lines-of-code-29af62440285?source=rss-54331e40d213------2</link>
            <guid isPermaLink="false">https://medium.com/p/29af62440285</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[sharedpreferences]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Krupal Shah]]></dc:creator>
            <pubDate>Mon, 05 Jun 2017 17:38:41 GMT</pubDate>
            <atom:updated>2019-10-21T17:03:15.486Z</atom:updated>
            <content:encoded><![CDATA[<figure><a href="https://commons.wikimedia.org/wiki/File:Kotlin_Island_west_side.jpg"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ybjK6Qp53ZJeOIzpNRh6mQ.jpeg" /></a></figure><p>If you were developing Android apps in Java until now and haven’t started using Kotlin in production yet, you may have some sort of utility classes for many things like File I/O, Connectivity, Cache, Shared Preferences etc. Today I am going to talk only about Shared Prefs and how we can use Kotlin to refactor our old Java utility classes. This post is intended for anyone including beginners who want to play around Kotlin.</p><p>Maybe you have a good solution for shared preferences but I have it copied from <a href="https://github.com/esripdx/Android-Static-Utils/blob/master/src/com/esri/android/util/SharedPrefsUtils.java">here</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92f7d1d1b2a7638e32fa54034db846a7/href">https://medium.com/media/92f7d1d1b2a7638e32fa54034db846a7/href</a></iframe><p>It looks ugly. To edit preferences, I had to write same things repetitively. Also, to access and manipulate; there are separate setters and getters for each type. In below steps, we will first try to refactor our Java class and then convert it to Kotlin.</p><h4>Step 1: Higher-order functions</h4><p>The first step we can do is to identify a repetitive task that has been performing. In our case, every time we put something in preferences, we open an editor, put value and either calling commit() or apply() over it. Instead, we can compose a higher-order function that would accept a function to be performed by the editor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd84db699056a4b5dfe7ffb60c3cd6b2/href">https://medium.com/media/dd84db699056a4b5dfe7ffb60c3cd6b2/href</a></iframe><p>Here, the Performer is a <a href="https://www.oreilly.com/learning/java-8-functional-interfaces">functional interface</a> and edit method takes an anonymous function as an argument. After doing that, we can remove some unnecessary code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/116949f1ca61d6cfbb080095d36351fe/href">https://medium.com/media/116949f1ca61d6cfbb080095d36351fe/href</a></iframe><h4>Step 2: Using generics</h4><p>Even after using lambdas, we have methods for each data type, which is not so good. We can use generics to have conditional checks for the type at run time. Either using instanceOf or using parametrizable class(class&lt;?&gt;), we can avoid writing a separate method for each type:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63ffee62938e4007f43c705ce3d0f0f4/href">https://medium.com/media/63ffee62938e4007f43c705ce3d0f0f4/href</a></iframe><p>Finally, we can manipulate preferences with just two methods :getValue() and setValue(). Also, our class looks less ugly and concise than previous.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e744ad39140f5129554b3c10047a2989/href">https://medium.com/media/e744ad39140f5129554b3c10047a2989/href</a></iframe><p>However, this if…else still looks bad. Many things like checking for nulls etc. are omitted. There are three to four parameters to pass in every single method. That interface for higher order function is unnecessary. We can not refactor those things because of limitations of the language.</p><h3>Converting to Kotlin</h3><h4>Step 3: Using extension functions</h4><p>In the Java version of our class, we were using all static methods. We can now convert them to powerful e<a href="https://kotlinlang.org/docs/reference/extensions.html">xtension functions</a>. So, in our case, we will first convert our edit() function as an extension for SharedPreferences:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bc296434d370bbf1761d668644405d0/href">https://medium.com/media/3bc296434d370bbf1761d668644405d0/href</a></iframe><p>As we can pass function directly as an argument in Kotlin, we can get rid of that Performer interface. Here I used inline keyword to avoid the cost of higher-order functions. You can read more about it <a href="https://kotlinlang.org/docs/reference/inline-functions.html">here</a>.</p><h4>Step 4: Using when expressions and reified types</h4><p>Using <a href="https://kotlinlang.org/docs/reference/control-flow.html#when-expression">when expressions</a>, we can eliminate all those if…else hell and make our setter look like below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5109be5ab3ddb16bf528f0b85cb8a292/href">https://medium.com/media/5109be5ab3ddb16bf528f0b85cb8a292/href</a></iframe><p>Well, but what about getValue()? In the Java version, we were using parameterizable class (class&lt;T&gt;). In Kotlin, we can do the same thing but with more elegantly using <a href="https://kotlinlang.org/docs/reference/inline-functions.html#reified-type-parameters">reified type parameters</a>. To put simply, it will allow us to use type passed as a parameter. You can read more about it <a href="https://antonioleiva.com/reified-types-kotlin/">here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7d5ceb97ee73e9014968a7a60a97637/href">https://medium.com/media/b7d5ceb97ee73e9014968a7a60a97637/href</a></iframe><p>Look at the following part:</p><p>getInt(key, defaultValue as? Int ?: -1)</p><p>Here, as? is a safe cast operator and so it returns null if type cast is failed. ?: is an elvis operator. It simply says: ‘take this value if the original value is null’. In our function parameter, defaultValue is the optional parameter and initialized to null. As a result, even if we don’t pass the default value, it will take from the right-hand side of the elvis operator.</p><h4>Step 5: operator functions</h4><p>So, our implementation now looks like below. Notice that I have added methods for accessing default as well as custom preferences and used <a href="https://kotlinlang.org/docs/reference/object-declarations.html">object declaration</a> to make it work as a singleton.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a179ab56b6327479e5d8aba683370f86/href">https://medium.com/media/a179ab56b6327479e5d8aba683370f86/href</a></iframe><p>Wouldn’t it be great if we rename our setter and getter to just set() and get()? Kotlin supports <a href="https://kotlinlang.org/docs/reference/operator-overloading.html#indexed">operator overloading</a> and so we can convert function to look like an operator.</p><p>Our final implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1e457db8d1917df8f6123f427e4838f/href">https://medium.com/media/a1e457db8d1917df8f6123f427e4838f/href</a></iframe><p>Now we can use square brackets for setting and getting values. Just two lines of code for manipulating shared preferences.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/605edd3e32b5a8c0d48e33e98ab442ac/href">https://medium.com/media/605edd3e32b5a8c0d48e33e98ab442ac/href</a></iframe><p>It looks neat and elegant. Thanks to Kotlin!</p><p><strong>Edit </strong>: Please refer to following gist for detailed example of usage:</p><p><a href="https://gist.github.com/krupalshah/d091be195999a7ddf52c3bb0f04f2bf3">https://gist.github.com/krupalshah/d091be195999a7ddf52c3bb0f04f2bf3</a></p><p><em>This post was originally published on my </em><a href="https://bytesunwired.wordpress.com/2017/06/04/manipulating-shared-prefs-with-kotlin-just-two-lines-of-code/"><em>blog</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29af62440285" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>