<?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"><channel><title><![CDATA[Mansi Vaghela's blog]]></title><description><![CDATA[Mansi Vaghela's blog]]></description><link>https://blog.mansi.dev</link><generator>RSS for Node</generator><lastBuildDate>Tue, 14 Apr 2026 06:18:02 GMT</lastBuildDate><atom:link href="https://blog.mansi.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Kotlin Keywords]]></title><description><![CDATA[Kotlin is a modern programming language that was first introduced by JetBrains in 2011. Since then, Kotlin has gained a lot of popularity among developers due to its concise syntax, null safety, and interoperability with Java. One of the most importa...]]></description><link>https://blog.mansi.dev/kotlin-keywords</link><guid isPermaLink="true">https://blog.mansi.dev/kotlin-keywords</guid><category><![CDATA[Android]]></category><category><![CDATA[android app development]]></category><category><![CDATA[Developer]]></category><category><![CDATA[development]]></category><category><![CDATA[Kotlin]]></category><dc:creator><![CDATA[Mansi Vaghela]]></dc:creator><pubDate>Wed, 26 Apr 2023 10:40:28 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1682505569198/1fbb2710-ce46-42f5-bf55-47f45c4af457.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Kotlin is a modern programming language that was first introduced by JetBrains in 2011. Since then, Kotlin has gained a lot of popularity among developers due to its concise syntax, null safety, and interoperability with Java. One of the most important aspects of any programming language is its keywords. Keywords are reserved words that have a special meaning in the language and cannot be used as identifiers or variable names. In this blog, we will discuss some of the most important keywords in Kotlin.</p>
<h1 id="heading-val-and-var"><strong>val and var</strong></h1>
<p>In Kotlin, variables can be declared using either val or var. The val keyword is used to declare immutable variables, which means that their value cannot be changed once they are assigned. On the other hand, the var keyword is used to declare mutable variables, which means that their value can be changed.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> name = <span class="hljs-string">"John"</span> <span class="hljs-comment">// immutable variable</span>
<span class="hljs-keyword">var</span> age = <span class="hljs-number">25</span> <span class="hljs-comment">// mutable variable</span>
</code></pre>
<h1 id="heading-if-and-else"><strong>if and else</strong></h1>
<p>The if and else keywords are used for conditional statements in Kotlin. They work in a similar way as in other programming languages. The if statement is used to check a condition, and if the condition is true, the code inside the if block is executed. If the condition is false, the code inside the else block is executed.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> num = <span class="hljs-number">10</span>
<span class="hljs-keyword">if</span>(num &gt; <span class="hljs-number">0</span>){
    println(<span class="hljs-string">"Positive number"</span>)
}
<span class="hljs-keyword">else</span>{
    println(<span class="hljs-string">"Negative number"</span>)
}
</code></pre>
<h1 id="heading-when"><strong>when</strong></h1>
<p>The when keyword is used for making decisions based on multiple conditions. It works like a switch statement in other programming languages. You can provide multiple cases and their corresponding actions using the when keyword.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> num = <span class="hljs-number">2</span>
<span class="hljs-keyword">when</span>(num){
    <span class="hljs-number">1</span> -&gt; println(<span class="hljs-string">"One"</span>)
    <span class="hljs-number">2</span> -&gt; println(<span class="hljs-string">"Two"</span>)
    <span class="hljs-number">3</span> -&gt; println(<span class="hljs-string">"Three"</span>)
    <span class="hljs-keyword">else</span> -&gt; println(<span class="hljs-string">"Invalid number"</span>)
}
</code></pre>
<h1 id="heading-fun"><strong>fun</strong></h1>
<p>The fun keyword is used to define functions in Kotlin. Functions are a group of statements that perform a specific task. You can define a function with or without parameters.</p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">greet</span><span class="hljs-params">(name: <span class="hljs-type">String</span>)</span></span>{
    println(<span class="hljs-string">"Hello, <span class="hljs-variable">$name</span>!"</span>)
}
greet(<span class="hljs-string">"John"</span>)
</code></pre>
<h1 id="heading-class-and-object"><strong>class and object</strong></h1>
<p>In Kotlin, class and object are used to define data types. A class is a blueprint for objects, while an object is an instance of a class. You can define properties and functions inside a class, and then create objects of that class to access those properties and functions.</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span></span>(<span class="hljs-keyword">val</span> name: String, <span class="hljs-keyword">var</span> age: <span class="hljs-built_in">Int</span>)

<span class="hljs-keyword">val</span> person = Person(<span class="hljs-string">"John"</span>, <span class="hljs-number">25</span>)
println(person.name) <span class="hljs-comment">// John</span>

person.age = <span class="hljs-number">30</span>
println(person.age) <span class="hljs-comment">// 30</span>
</code></pre>
<h1 id="heading-return"><strong>return</strong></h1>
<p>The return keyword is used to return a value from a function. It is also used to exit a loop or a block of code early.</p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">add</span><span class="hljs-params">(num1: <span class="hljs-type">Int</span>, num2: <span class="hljs-type">Int</span>)</span></span>: <span class="hljs-built_in">Int</span>{
    <span class="hljs-keyword">return</span> num1 + num2
}
<span class="hljs-keyword">val</span> result = add(<span class="hljs-number">5</span>, <span class="hljs-number">3</span>)
println(result) <span class="hljs-comment">// 8</span>
</code></pre>
<p>In conclusion, Kotlin has a set of powerful and easy-to-use keywords that make it an excellent programming language for developers. The keywords we have discussed in this blog are just a few of the many that Kotlin offers, but they are essential for understanding the language's fundamentals. If you're interested in learning more about Kotlin, you can explore the official documentation and start building your own applications.</p>
<p>I greatly thank you for your time.</p>
<p><em>If you want to read more content like this, please go check out my profile.</em></p>
<p><a class="user-mention" href="https://hashnode.com/@mansivaghela">Mansi Vaghela</a> <a target="_blank" href="https://www.linkedin.com/in/mansi-droid/"><strong>LinkedIn</strong></a> <a target="_blank" href="https://twitter.com/mansi_droid"><strong>Twitter</strong></a> <a target="_blank" href="https://github.com/mansi-droid"><strong>Github</strong></a> <a target="_blank" href="https://www.youtube.com/channel/UCoGcTjvUp32To72hQVe7iZw"><strong>Youtube</strong></a></p>
]]></content:encoded></item><item><title><![CDATA[Using Scoped Functions in Kotlin - let, run, with, also, apply]]></title><description><![CDATA[Now that almost all Android developers have switched from Java to Kotlin, they are finding how much easier, cleaner, and more concise Kotlin is than Java. Kotlin introduces a number of developer-friendly features for less code, reducing the number of...]]></description><link>https://blog.mansi.dev/using-scoped-functions-in-kotlin-let-run-with-also-apply</link><guid isPermaLink="true">https://blog.mansi.dev/using-scoped-functions-in-kotlin-let-run-with-also-apply</guid><category><![CDATA[Android]]></category><category><![CDATA[android app development]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[Developer]]></category><category><![CDATA[development]]></category><dc:creator><![CDATA[Mansi Vaghela]]></dc:creator><pubDate>Wed, 22 Mar 2023 10:11:25 GMT</pubDate><content:encoded><![CDATA[<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679480384426/279c3545-c0b8-49c3-bf6e-59f00aad57e6.png" alt class="image--center mx-auto" /></p>
<p>Now that almost all Android developers have switched from Java to Kotlin, they are finding how much easier, cleaner, and more concise Kotlin is than Java. Kotlin introduces a number of developer-friendly features for less code, reducing the number of problems.</p>
<p>Kotlin is a modern, concise and powerful programming language that has gained immense popularity in recent years. One of the reasons for its success is its support for functional programming concepts. In this blog, we will explore important higher-order functions in Kotlin: let, run, also and apply.</p>
<h2 id="heading-the-let-function"><strong>The let function</strong></h2>
<p>The let function is a higher-order function that takes a lambda expression as an argument and executes it with the value of the calling object as its argument. The result of the lambda expression is then returned. Let's take a look at an example:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> name: String? = <span class="hljs-string">"John Doe"</span>

<span class="hljs-keyword">val</span> result = name?.let {
    <span class="hljs-string">"Hello, <span class="hljs-variable">$it</span>!"</span>
} ?: <span class="hljs-string">"Unknown"</span>

println(result) <span class="hljs-comment">// Output: Hello, John Doe!</span>
</code></pre>
<p>In this example, we use the safe call operator to ensure that the let function is only called if the <code>name</code> variable is not null. The lambda expression in the let function concatenates the string "Hello, " with the value of <code>it</code>, which is the non-null value of <code>name</code>. If <code>name</code> is null, the <code>?:</code> operator returns the default value of "Unknown".</p>
<h2 id="heading-the-run-function"><strong>The run function</strong></h2>
<p>The run function is similar to the let function in that it takes a lambda expression as an argument and executes it with the value of the calling object as its argument. However, the difference is that the run function does not return the result of the lambda expression, but instead returns the calling object itself. Here's an example:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> numbers = mutableListOf&lt;<span class="hljs-built_in">Int</span>&gt;(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>)

<span class="hljs-keyword">val</span> sum = numbers.run {
    add(<span class="hljs-number">5</span>)
    add(<span class="hljs-number">6</span>)
    sum()
}

println(sum) <span class="hljs-comment">// Output: 21</span>
</code></pre>
<p>In this example, we use the run function to add two numbers to the <code>numbers</code> list and then calculate the sum of all the elements in the list using the <code>sum()</code> function. The result of the <code>sum()</code> function is returned by the run function, but since it doesn't matter in this case, we ignore it.</p>
<h2 id="heading-the-also-function"><strong>The also function</strong></h2>
<p>The also function is similar to the let function in that it takes a lambda expression as an argument and executes it with the value of the calling object as its argument. However, the difference is that the also function does not return the result of the lambda expression, but instead returns the calling object itself. Here's an example:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> message = <span class="hljs-string">"Hello, World!"</span>

<span class="hljs-keyword">val</span> result = message.also {
    println(it)
}.length

println(result) <span class="hljs-comment">// Output: 13</span>
</code></pre>
<p>In this example, we use the also function to print the value of the <code>message</code> variable and then return its length. The <code>it</code> parameter in the lambda expression refers to the value of the <code>message</code> variable. Since the also function returns the calling object, we can chain other functions after it.</p>
<h2 id="heading-the-apply-function"><strong>The apply function</strong></h2>
<p>The apply function is similar to the run function in that it takes a lambda expression as an argument and executes it with the value of the calling object as its argument. However, the difference is that the apply function returns the calling object itself, rather than the result of the lambda expression. Here's an example:</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span></span>(<span class="hljs-keyword">var</span> name: String, <span class="hljs-keyword">var</span> age: <span class="hljs-built_in">Int</span>)

<span class="hljs-keyword">val</span> person = Person(<span class="hljs-string">"John Doe"</span>, <span class="hljs-number">30</span>).apply {
    age += <span class="hljs-number">1</span>
}

println(person.age) <span class="hljs-comment">// Output: 31</span>
</code></pre>
<p>In this example, we use the apply function to create a <code>Person</code> object with the name "John Doe" and the age 30. We then use the apply function to increment the age of the <code>person</code> object by 1. Since the apply function returns</p>
<p>All there is to know about Kotlin's Scoped functions. We hope that our blog has provided you with a greater understanding of and a method for constructing the proper scoped function in the right place, even though we may be using this in our code.</p>
<p>I greatly thank you for your time.</p>
<p><em>If you want to read more content like this, please go check out my profile.</em></p>
<p><a class="user-mention" href="https://hashnode.com/@mansivaghela">Mansi Vaghela</a> <a target="_blank" href="https://www.linkedin.com/in/mansi-droid/"><strong>LinkedIn</strong></a> <a target="_blank" href="https://twitter.com/mansi_droid"><strong>Twitter</strong></a> <a target="_blank" href="https://github.com/mansi-droid"><strong>Github</strong></a> <a target="_blank" href="https://www.youtube.com/channel/UCoGcTjvUp32To72hQVe7iZw"><strong>Youtube</strong></a></p>
]]></content:encoded></item><item><title><![CDATA[lateinit vs lazy in Kotlin]]></title><description><![CDATA[In this blog, we will learn about the lateinit vs lazy properties in Kotlin.
In Kotlin, there are two ways to initialize a property that is not available at the time of object creation: lateinit and lazy. Both of these keywords allow you to postpone ...]]></description><link>https://blog.mansi.dev/lateinit-vs-lazy-in-kotlin</link><guid isPermaLink="true">https://blog.mansi.dev/lateinit-vs-lazy-in-kotlin</guid><category><![CDATA[android app development]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[Android]]></category><category><![CDATA[Developer]]></category><category><![CDATA[development]]></category><dc:creator><![CDATA[Mansi Vaghela]]></dc:creator><pubDate>Wed, 08 Mar 2023 09:55:53 GMT</pubDate><content:encoded><![CDATA[<p>In this blog, we will learn about the <code>lateinit</code> vs <code>lazy</code> properties in Kotlin.</p>
<p>In Kotlin, there are two ways to initialize a property that is not available at the time of object creation: <code>lateinit</code> and <code>lazy</code>. Both of these keywords allow you to postpone the initialization of a property until it is actually needed, but they work in slightly different ways. In this blog, we will compare and contrast <code>lateinit</code> vs <code>lazy</code> and discuss when to use each.</p>
<h3 id="heading-lateinit"><strong>lateinit</strong></h3>
<p><code>lateinit</code> is a keyword that allows you to declare a non-null property without initializing it immediately. You can then initialize the property at a later time, as long as you do so before you try to access it. The most common use case for <code>lateinit</code> is when we are working with dependency injection frameworks like Dagger or Koin, where the initialization of certain properties might be deferred until runtime.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">lateinit</span> <span class="hljs-keyword">var</span> myObject: MyObject

<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">initializeMyObject</span><span class="hljs-params">()</span></span> {
    myObject = MyObject()
}
</code></pre>
<p>There are a few things to keep in mind when using <code>lateinit</code>:</p>
<ul>
<li><p>The property must be a non-null type, or else you'll get a compilation error.</p>
</li>
<li><p>You can only use <code>lateinit</code> with properties that are declared at the class level (i.e., not local variables).</p>
</li>
<li><p>If you try to access a <code>lateinit</code> property before it has been initialized, you'll get a <code>lateinit</code> exception at runtime.</p>
</li>
</ul>
<h3 id="heading-lazy"><strong>lazy</strong></h3>
<p><code>lazy</code> is a keyword that allows you to declare a property whose initialization is deferred until the first time it is accessed. The property is then cached, so subsequent accesses to the property will return the same value without re-initializing it. This is useful when you have expensive initialization logic that you don't want to perform unnecessarily.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> myObject: MyObject <span class="hljs-keyword">by</span> lazy {
    MyObject()
}
</code></pre>
<p>When using <code>lazy</code>, you should keep the following in mind:</p>
<ul>
<li><p>The property must be declared with <code>val</code>, not <code>var</code>.</p>
</li>
<li><p>You can only use <code>lazy</code> with properties that are declared at the class level (i.e., not local variables).</p>
</li>
<li><p>The initialization logic should be thread-safe, as <code>lazy</code> properties are only initialized once and can be accessed by multiple threads.</p>
</li>
</ul>
<h3 id="heading-when-to-use-each"><strong>When to use each</strong></h3>
<p>So, when should we use <code>lateinit</code> vs <code>lazy</code>? Here are some guidelines:</p>
<ul>
<li><p>Use <code>lateinit</code> when we need to declare a non-null property that cannot be initialized immediately, but we know it will be initialized before it is accessed. For example, if we are working with a dependency injection framework, we might use <code>lateinit</code> for properties that are injected at runtime.</p>
</li>
<li><p>Use <code>lazy</code> when we need to declare a property that might not be accessed immediately, and we want to avoid unnecessary initialization. For example, if we have an expensive operation that calculates a property value, we might use <code>lazy</code> to ensure that it is only calculated when it is actually needed.</p>
</li>
</ul>
<p>In summary, <code>lateinit</code> and <code>lazy</code> are two powerful tools that can help you write cleaner and more efficient Kotlin code. By understanding the differences between the two and knowing when to use each, we can write code that is both more correct and more performant.</p>
<p><em>If you want to read more content like this, please go check out my profile.</em></p>
<p><a class="user-mention" href="https://hashnode.com/@mansivaghela">Mansi Vaghela</a> <a target="_blank" href="https://www.linkedin.com/in/mansi-droid/"><strong>LinkedIn</strong></a> <a target="_blank" href="https://twitter.com/mansi_droid"><strong>Twitter</strong></a> <a target="_blank" href="https://github.com/mansi-droid"><strong>Github</strong></a> <a target="_blank" href="https://www.youtube.com/channel/UCoGcTjvUp32To72hQVe7iZw"><strong>Youtube</strong></a></p>
]]></content:encoded></item><item><title><![CDATA[Difference between AndroidViewModel and ViewModel]]></title><description><![CDATA[In this blog, we will discuss the difference between AndroidViewModel and ViewModel.
In the Android Jetpack architecture components, ViewModel and AndroidViewModel are two classes that are used to manage UI-related data across configuration changes. ...]]></description><link>https://blog.mansi.dev/difference-between-androidviewmodel-and-viewmodel</link><guid isPermaLink="true">https://blog.mansi.dev/difference-between-androidviewmodel-and-viewmodel</guid><category><![CDATA[Android]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[Jetpack Compose]]></category><category><![CDATA[Developer]]></category><category><![CDATA[android app development]]></category><dc:creator><![CDATA[Mansi Vaghela]]></dc:creator><pubDate>Thu, 23 Feb 2023 15:44:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1677166886869/a2fdc1e3-9346-4d00-ae5a-24e990454afd.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this blog, we will discuss the difference between AndroidViewModel and ViewModel.</p>
<p>In the Android Jetpack architecture components, <code>ViewModel</code> and <code>AndroidViewModel</code> are two classes that are used to manage UI-related data across configuration changes. Both classes provide a way to separate the UI logic from the data logic and manage the state of the UI.</p>
<p>The primary difference between <code>ViewModel</code> and <code>AndroidViewModel</code> is that <code>AndroidViewModel</code> is a subclass of <code>ViewModel</code> that includes a reference to the <code>Application</code> context, while <code>ViewModel</code> does not.</p>
<p>Let's take a closer look at each class and how they are used in Android app development.</p>
<h2 id="heading-viewmodel"><strong>ViewModel</strong></h2>
<p><code>ViewModel</code> is designed to be used with data that is specific to the UI and does not require access to the <code>Application</code> context. It is typically used to store and manage UI-related data that is not persistent, such as the state of a UI component or data that is fetched from a remote server.</p>
<p>For example, let's say we have a simple Android app that displays a list of items fetched from a remote server. We can create a <code>ViewModel</code> class to manage the data and the state of the UI:</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ItemListViewModel</span> : <span class="hljs-type">ViewModel</span></span>() {
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> repository = ItemRepository()

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> _itemList = MutableLiveData&lt;List&lt;Item&gt;&gt;()
    <span class="hljs-keyword">val</span> itemList: LiveData&lt;List&lt;Item&gt;&gt;
        <span class="hljs-keyword">get</span>() = _itemList

    <span class="hljs-keyword">init</span> {
        fetchItemList()
    }

    <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">fetchItemList</span><span class="hljs-params">()</span></span> {
        viewModelScope.launch {
            <span class="hljs-keyword">val</span> itemList = repository.fetchItemList()
            _itemList.value = itemList
        }
    }
}
</code></pre>
<p>In this example, we have a <code>ViewModel</code> class called <code>ItemListViewModel</code> that fetches a list of items from a remote server and stores the result in a <code>LiveData</code> object called <code>itemList</code>. The <code>init</code> block is called when the <code>ViewModel</code> is created, and it triggers the <code>fetchItemList()</code> method to fetch the data.</p>
<h2 id="heading-androidviewmodel"><strong>AndroidViewModel</strong></h2>
<p><code>AndroidViewModel</code> is designed to be used with data that requires access to the <code>Application</code> context, such as data that is stored in a local database or shared preferences. It provides a way to access the <code>Application</code> context without passing it through the UI components, which can cause memory leaks.</p>
<p>For example, let's say we have an Android app that uses a local database to store user data. We can create an <code>AndroidViewModel</code> class to manage the data and the state of the UI:</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserViewModel</span></span>(application: Application) : AndroidViewModel(application) {
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> repository = UserRepository(application)

    <span class="hljs-keyword">val</span> userList: LiveData&lt;List&lt;User&gt;&gt; = repository.getUserList()

    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">insertUser</span><span class="hljs-params">(user: <span class="hljs-type">User</span>)</span></span> {
        repository.insertUser(user)
    }
}
</code></pre>
<p>In this example, we have an <code>AndroidViewModel</code> class called <code>UserViewModel</code> that manages a list of users stored in a local database. The <code>application</code> parameter is passed to the <code>AndroidViewModel</code> constructor to provide access to the <code>Application</code> context. The <code>userList</code> property is a <code>LiveData</code> object that contains the list of users, and the <code>insertUser()</code> method is used to add a new user to the database.</p>
<p>Conclusion</p>
<p>In summary, <code>ViewModel</code> and <code>AndroidViewModel</code> are both used to manage UI-related data in Android apps, but <code>AndroidViewModel</code> is designed for use with data that requires access to the <code>Application</code> context, while <code>ViewModel</code> is used for data that is specific to the UI and does not need access to the <code>Application</code> context. Both classes provide a way to separate the UI logic from the data logic and manage the state of the UI across configuration changes.</p>
<p><em>If you want to read more content like this, please go check out my profile.</em></p>
<p><a class="user-mention" href="https://hashnode.com/@mansivaghela">Mansi Vaghela</a> <a target="_blank" href="https://www.linkedin.com/in/mansi-droid/"><strong>LinkedIn</strong></a> <a target="_blank" href="https://twitter.com/mansi_droid"><strong>Twitter</strong></a> <a target="_blank" href="https://github.com/mansi-droid"><strong>Github</strong></a> <a target="_blank" href="https://www.youtube.com/channel/UCoGcTjvUp32To72hQVe7iZw"><strong>Youtube</strong></a></p>
]]></content:encoded></item><item><title><![CDATA[How to Make the Firebase Database SDK Work Better With Kotlin]]></title><description><![CDATA[In this article, we are going straight to the point. 🚀
I want to share some extension functions to make your experience with the Firebase Database a little more comfortable with Kotlin.
We are going to make reusable code that is also going to avoid ...]]></description><link>https://blog.mansi.dev/how-to-make-the-firebase-database-sdk-work-better-with-kotlin</link><guid isPermaLink="true">https://blog.mansi.dev/how-to-make-the-firebase-database-sdk-work-better-with-kotlin</guid><category><![CDATA[Firebase]]></category><category><![CDATA[Databases]]></category><category><![CDATA[Android]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[android app development]]></category><dc:creator><![CDATA[Mansi Vaghela]]></dc:creator><pubDate>Mon, 13 Feb 2023 12:44:49 GMT</pubDate><content:encoded><![CDATA[<p>In this article, we are going straight to the point. 🚀</p>
<p>I want to share some extension functions to make your experience with the Firebase Database a little more comfortable with Kotlin.</p>
<p>We are going to make reusable code that is also going to avoid the need for callbacks and take advantage of <code>suspend</code> functions.</p>
<h4 id="heading-mapping-operations"><strong>Mapping operations</strong></h4>
<p>Here is a function to cast the value of every node in the database to whatever object you need. Thanks to the reified and inline keywords, you can make this transformation in one line with clear looking code.</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">// This would be called like so, snapshot.toDomain&lt;String&gt;()</span>

<span class="hljs-keyword">inline</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-type">&lt;<span class="hljs-keyword">reified</span> T&gt;</span> DataSnapshot.<span class="hljs-title">toDomain</span><span class="hljs-params">()</span></span>: T? = getValue(T::<span class="hljs-keyword">class</span>.java)
</code></pre>
<h4 id="heading-read-operations"><strong>Read operations</strong></h4>
<p>For one-shot read operations, you can use the following function. In all the methods that you are going to see in this post, an exception is going to be thrown if the operation fails, so take that into account when using them.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">suspend</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> DatabaseReference.<span class="hljs-title">read</span><span class="hljs-params">()</span></span>: DataSnapshot = suspendCoroutine { continuation -&gt;
    <span class="hljs-keyword">val</span> valueEventListener = <span class="hljs-keyword">object</span> : ValueEventListener {
        <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onCancelled</span><span class="hljs-params">(error: <span class="hljs-type">DatabaseError</span>)</span></span> {
            continuation.resumeWithException(error.toException())
        }

        <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onDataChange</span><span class="hljs-params">(snapshot: <span class="hljs-type">DataSnapshot</span>)</span></span> {
            continuation.resume(snapshot)
        }
    }
    addListenerForSingleValueEvent(valueEventListener)
}
</code></pre>
<p>To subscribe to changes in the database, we have the following function that listen to node children, returns a <code>Flow</code> than be collected every time a node creation happens.</p>
<p>To make it a little more interesting, I made it so that you can pass it a mapper function instead of doing the mapping outside.</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">/* This function can be called like 
 * subscribeModifiedChildren(DataSnapshot::toBoolean)
 * where toBoolean is 
 * fun toBoolean() = toDomain&lt;Boolean&gt;() ?: false
 */</span>

<span class="hljs-keyword">suspend</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-type">&lt;T&gt;</span> DatabaseReference.<span class="hljs-title">subscribeNewChildren</span><span class="hljs-params">(
    mapper: <span class="hljs-type">DataSnapshot</span>.() -&gt; <span class="hljs-type">T</span>
)</span></span>: Flow&lt;T&gt; = callbackFlow {
    <span class="hljs-keyword">val</span> childEventListener = <span class="hljs-keyword">object</span> : ChildEventListener {
        <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onChildAdded</span><span class="hljs-params">(snapshot: <span class="hljs-type">DataSnapshot</span>, previousChildName: <span class="hljs-type">String</span>?)</span></span> {
            trySend(snapshot.mapper())
        }

        <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onChildChanged</span><span class="hljs-params">(snapshot: <span class="hljs-type">DataSnapshot</span>, previousChildName: <span class="hljs-type">String</span>?)</span></span> {}

        <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onChildRemoved</span><span class="hljs-params">(snapshot: <span class="hljs-type">DataSnapshot</span>)</span></span> {}

        <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onChildMoved</span><span class="hljs-params">(snapshot: <span class="hljs-type">DataSnapshot</span>, previousChildName: <span class="hljs-type">String</span>?)</span></span> {}

        <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onCancelled</span><span class="hljs-params">(error: <span class="hljs-type">DatabaseError</span>)</span></span> {}
    }
    addChildEventListener(childEventListener)
    awaitClose {
        removeEventListener(childEventListener)
    }
}
</code></pre>
<p>In this next method, we have the same idea as above, but now we are listening changes to a specific node.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@OptIn(InternalCoroutinesApi::class)</span>
<span class="hljs-keyword">suspend</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-type">&lt;T&gt;</span> DatabaseReference.<span class="hljs-title">subscribeModifiedChildren</span><span class="hljs-params">(
    mapper: <span class="hljs-type">DataSnapshot</span>.() -&gt; <span class="hljs-type">T</span>
)</span></span>: Flow&lt;T&gt; = callbackFlow {
    <span class="hljs-keyword">val</span> valueEventListener = <span class="hljs-keyword">object</span> : ValueEventListener {
        <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onCancelled</span><span class="hljs-params">(error: <span class="hljs-type">DatabaseError</span>)</span></span> {
            handleCoroutineException(coroutineContext, error.toException())
        }

        <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onDataChange</span><span class="hljs-params">(snapshot: <span class="hljs-type">DataSnapshot</span>)</span></span> {
            trySend(snapshot.mapper())
        }
    }
    addValueEventListener(valueEventListener)
    awaitClose {
        removeEventListener(valueEventListener)
    }
}
</code></pre>
<p>For queries, we do exactly the same as the read operation, but we extend from the <code>Query</code> object.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">suspend</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> Query.<span class="hljs-title">read</span><span class="hljs-params">()</span></span>: DataSnapshot = suspendCoroutine { continuation -&gt;
    <span class="hljs-keyword">val</span> valueEventListener = <span class="hljs-keyword">object</span> : ValueEventListener {
        <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onCancelled</span><span class="hljs-params">(error: <span class="hljs-type">DatabaseError</span>)</span></span> {
            continuation.resumeWithException(error.toException())
        }

        <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onDataChange</span><span class="hljs-params">(snapshot: <span class="hljs-type">DataSnapshot</span>)</span></span> {
            continuation.resume(snapshot)
        }
    }
    addListenerForSingleValueEvent(valueEventListener)
}
</code></pre>
<h4 id="heading-write-operations"><strong>Write operations</strong></h4>
<p>The write operation uses the <code>suspendCoroutine</code> again, but now we called the <code>setValue</code> method provided by the Firebase SDK.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">suspend</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-type">&lt;T&gt;</span> DatabaseReference.<span class="hljs-title">write</span><span class="hljs-params">(<span class="hljs-keyword">data</span>: <span class="hljs-type">T</span>)</span></span> {
    suspendCoroutine { continuation -&gt;
        setValue(<span class="hljs-keyword">data</span>)
            .addOnSuccessListener {
                continuation.resume(<span class="hljs-built_in">Unit</span>)
            }
            .addOnFailureListener {
                continuation.resumeWithException(it)
            }
    }
}
</code></pre>
<p>In case you want to get a node or create it if it doesn’t exist, you have the following functions. This is pretty useful, for example, if you need to add a new node when a user is trying to register in your app, but he did sign up before and didn’t remember.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">suspend</span> <span class="hljs-keyword">inline</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-type">&lt;<span class="hljs-keyword">reified</span> T&gt;</span> DatabaseReference.<span class="hljs-title">getOrCreate</span><span class="hljs-params">(<span class="hljs-keyword">data</span>: <span class="hljs-type">T</span>)</span></span>: DataSnapshot =
    suspendCoroutine { continuation -&gt;
        <span class="hljs-keyword">val</span> transactionHandler = <span class="hljs-keyword">object</span> : Transaction.Handler {
            <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">doTransaction</span><span class="hljs-params">(currentData: <span class="hljs-type">MutableData</span>)</span></span>: Transaction.Result {
                <span class="hljs-keyword">return</span> <span class="hljs-keyword">if</span> (currentData.getValue&lt;Any&gt;() != <span class="hljs-literal">null</span>) {
                    Transaction.success(currentData)
                } <span class="hljs-keyword">else</span> {
                    currentData.value = <span class="hljs-keyword">data</span>
                    Transaction.success(currentData)
                }
            }

            <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onComplete</span><span class="hljs-params">(
                error: <span class="hljs-type">DatabaseError</span>?,
                committed: <span class="hljs-type">Boolean</span>,
                currentData: <span class="hljs-type">DataSnapshot</span>?
            )</span></span> {
                <span class="hljs-keyword">if</span> (committed &amp;&amp; currentData != <span class="hljs-literal">null</span>) {
                    continuation.resume(currentData)
                } <span class="hljs-keyword">else</span> {
                    error?.let { <span class="hljs-keyword">throw</span> error.toException() }
                }
            }
        }
        runTransaction(transactionHandler)
    }
</code></pre>
<h4 id="heading-delete-operations"><strong>Delete operations</strong></h4>
<p>To finish, here is a delete operation. We are going to follow the same technique used in the <code>write</code> function, so that we can know if the operation was completed successfully or if we need to manage the error.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">suspend</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> DatabaseReference.<span class="hljs-title">delete</span><span class="hljs-params">()</span></span> {
    suspendCoroutine { continuation -&gt;
        removeValue()
            .addOnSuccessListener {
                continuation.resume(<span class="hljs-built_in">Unit</span>)
            }
            .addOnFailureListener {
                continuation.resumeWithException(it)
            }
    }
}
</code></pre>
<p><em>If you want to read more content like this, please go check out my profile.</em></p>
<p><a class="user-mention" href="https://hashnode.com/@mansivaghela">Mansi Vaghela</a> <a target="_blank" href="https://www.linkedin.com/in/mansi-droid/"><strong>LinkedIn</strong></a> <a target="_blank" href="https://twitter.com/mansi_droid"><strong>Twitter</strong></a> <a target="_blank" href="https://github.com/mansi-droid"><strong>Github</strong></a> <a target="_blank" href="https://www.youtube.com/channel/UCoGcTjvUp32To72hQVe7iZw"><strong>Youtube</strong></a></p>
]]></content:encoded></item><item><title><![CDATA[How to use Dagger 2 on Android with Kotlin]]></title><description><![CDATA[Virtually everyone who wants to create code on Android in a decoupled and easy-to-test way, resorts to Dagger sooner or later.
Although there is something that works a bit differently when setting up Dagger in Kotlin, most of it is quite simple, and ...]]></description><link>https://blog.mansi.dev/how-to-use-dagger-2-on-android-with-kotlin</link><guid isPermaLink="true">https://blog.mansi.dev/how-to-use-dagger-2-on-android-with-kotlin</guid><category><![CDATA[android app development]]></category><category><![CDATA[Android]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[Mobile Development]]></category><dc:creator><![CDATA[Mansi Vaghela]]></dc:creator><pubDate>Mon, 13 Feb 2023 12:17:30 GMT</pubDate><content:encoded><![CDATA[<p>Virtually everyone who wants to create code on Android in a decoupled and easy-to-test way, resorts to Dagger sooner or later.</p>
<p>Although there is something that works a bit differently when setting up Dagger in Kotlin, most of it is quite simple, and in a few steps I’m going to show you here today.</p>
<p>Also be aware that, thanks to the power of Kotlin, there are other ways to solve the injection, and even some libraries made exclusively in Kotlin for it.</p>
<p><strong>But Dagger is still a viable option and one of the most versatile (if not the most).</strong></p>
<h2 id="heading-configuring-the-project-to-use-dagger-2">Configuring the project to use Dagger 2</h2>
<p>If you’ve already configured the Kotlin plugin in your project, all you need to do is configure <code>kapt</code>.</p>
<p>If you already used Dagger, you probably know <code>apt</code>. <code>kapt</code> is just the version for Kotlin, which creates the necessary self-generated classes for Dagger.</p>
<p>To configure it, you need to add the following to <code>build.gradle</code>:</p>
<pre><code class="lang-kotlin">kapt {
    generateStubs = <span class="hljs-literal">true</span>
}
</code></pre>
<p>You can add it just before the <em>dependencies</em> section. If you want, you can instead use the new experimental plugin, which is pretty stable already:</p>
<pre><code class="lang-kotlin">apply plugin: <span class="hljs-string">'kotlin-kapt'</span>
</code></pre>
<p>Now you just need to add the dependencies of the Dagger compiler (using <code>kapt</code> to not be included in the apk) and the actual library:</p>
<pre><code class="lang-kotlin">kapt <span class="hljs-string">'com.google.dagger:dagger-compiler:2.5'</span>
compile <span class="hljs-string">'com.google.dagger:dagger:2.5'</span>
</code></pre>
<p>Everything is ready to start using Dagger.</p>
<h2 id="heading-main-module-implementation">Main module implementation</h2>
<p>As you may know, for the main graph you’ll need a <code>Module</code> and a <code>Component</code>.</p>
<p>The application module, in this simple example, will only return the instance of the application itself.</p>
<p>To do this we’ll create a class annotated with <code>@Module</code>, which will receive the application instance via constructor, store it in a property, and return it using a method annotated with <code>@Provides @Singleton</code>:</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Module</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AppModule</span></span>(<span class="hljs-keyword">val</span> app: App) {
    <span class="hljs-meta">@Provides</span> <span class="hljs-meta">@Singleton</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">provideApp</span><span class="hljs-params">()</span></span> = app
}
</code></pre>
<p>You can see that, even for this easy class, the code is much simpler than in Java.</p>
<p>Now we have to implement the <code>Component</code>, which needs an array of modules to load, and specifies who is going to be able to manually inject it:</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Singleton</span>
<span class="hljs-meta">@Component(modules = arrayOf(AppModule::class)</span>)
<span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">AppComponent</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">inject</span><span class="hljs-params">(app: <span class="hljs-type">App</span>)</span></span>
}
</code></pre>
<p>Just create the class <code>App</code>, which will be responsible of generating the graph:</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">App</span> : <span class="hljs-type">Application</span></span>() {

    <span class="hljs-keyword">val</span> component: AppComponent <span class="hljs-keyword">by</span> lazy {
        DaggerAppComponent
                .builder()
                .appModule(AppModule(<span class="hljs-keyword">this</span>))
                .build()
    }

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onCreate</span><span class="hljs-params">()</span></span> {
        <span class="hljs-keyword">super</span>.onCreate()
        component.inject(<span class="hljs-keyword">this</span>)
    }
}
</code></pre>
<p>The interesting thing to see here is that, thanks to the <code>lazy</code> statement, <strong>we can specify the value of the graph in the definition of the property</strong>, and thus get read-only access to that property.</p>
<p>The code defined by the property won’t be executed until <code>component.inject (this)</code> is done, so that by that time <code>this</code> already exists and can be created securely way.</p>
<h2 id="heading-one-module-implementation-per-scope">One module implementation per scope</h2>
<p>The modules by scope allow that part of the graph only to live during the lifetime of the object that creates it.</p>
<p>In this way, <strong>we can create subgraphs that live and die with an Activity</strong>, for example.</p>
<p>We would create our module with what we need:</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Module</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HomeModule</span></span>(<span class="hljs-keyword">val</span> activity: HomeActivity) {
}
</code></pre>
<p>A <code>Subcomponent</code> in a very similar way to the previous one, indicating that it’ll be injected into the <code>HomeActivity</code>:</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Singleton</span>
<span class="hljs-meta">@Subcomponent(modules = arrayOf(HomeModule::class)</span>)
<span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">HomeComponent</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">inject</span><span class="hljs-params">(activity: <span class="hljs-type">HomeActivity</span>)</span></span>
}
</code></pre>
<p>And a <code>plus</code> method in <code>AppComponent</code>, to indicate that this component can be added subcomponents of that type:</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">AppComponent</span> </span>{
    ...
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">plus</span><span class="hljs-params">(homeModule: <span class="hljs-type">HomeModule</span>)</span></span>: HomeComponent
}
</code></pre>
<p>Now, in the <code>HomeActivity</code> you only need to declare the subcomponent:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> component <span class="hljs-keyword">by</span> lazy { app.component.plus(HomeModule(<span class="hljs-keyword">this</span>)) }
</code></pre>
<p>And you can inject it after the <code>setContentView</code>:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onCreate</span><span class="hljs-params">(savedInstanceState: <span class="hljs-type">Bundle</span>?)</span></span> {
    <span class="hljs-keyword">super</span>.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    component.inject(<span class="hljs-keyword">this</span>)
}
</code></pre>
<p>If you’re wondering where <code>app</code> comes from, it’s a extension property that looks like this:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> Activity.app: App
    <span class="hljs-keyword">get</span>() = application <span class="hljs-keyword">as</span> App
</code></pre>
<p>It’s simply a way to avoid having to do casting every time you access <code>application</code> if you have your own custom one.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Dagger 2 is also easy to use in Kotlin. You no longer have an excuse to implement a great decoupled architecture in Kotlin.</p>
<p><a class="user-mention" href="https://hashnode.com/@mansivaghela">Mansi Vaghela</a> <a target="_blank" href="https://www.linkedin.com/in/mansi-droid/"><strong>LinkedIn</strong></a> <a target="_blank" href="https://twitter.com/mansi_droid"><strong>Twitter</strong></a> <a target="_blank" href="https://github.com/mansi-droid"><strong>Github</strong></a> <a target="_blank" href="https://www.youtube.com/channel/UCoGcTjvUp32To72hQVe7iZw">Youtube</a></p>
]]></content:encoded></item><item><title><![CDATA[How to Use the Kotlin Playground]]></title><description><![CDATA[As a modern Android developer, sometimes I find myself with the need of wanting to run some small snippet of code. For these kinds of situations, the lesser-known Kotlin Playground is a great option to try out code on the fly.
What is the Kotlin Play...]]></description><link>https://blog.mansi.dev/how-to-use-the-kotlin-playground</link><guid isPermaLink="true">https://blog.mansi.dev/how-to-use-the-kotlin-playground</guid><category><![CDATA[Android]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[android app development]]></category><category><![CDATA[Developer]]></category><category><![CDATA[development]]></category><dc:creator><![CDATA[Mansi Vaghela]]></dc:creator><pubDate>Fri, 10 Feb 2023 08:50:48 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1676017727367/40b58597-f74d-4685-990d-b56a9c31c969.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>As a modern Android developer, sometimes I find myself with the need of wanting to run some small snippet of code. For these kinds of situations, the lesser-known <strong>Kotlin Playground</strong> is a great option to try out code on the fly.</p>
<h1 id="heading-what-is-the-kotlin-playground"><strong>What is the Kotlin Playground?</strong></h1>
<p>Initially published about 5 years ago, the Kotlin Playground is an online lightweight compiler that allows Kotlin programmers to run code directly in the browser using different versions of Kotlin, and even target different platforms.</p>
<p>Additionally, the Kotlin Playground gives developers the opportunity to both share their code with other people, as well as embed a small version of the compiler into websites, and particularly into Medium.</p>
<h1 id="heading-how-does-it-work"><strong>How does it work?</strong></h1>
<p>Using the Kotlin standard libraries only, the Kotlin Playground can run mildly complex blocks of code directly in your browser without much setup, and without the burdensome matter of ramping up and working with a chunky IDE.</p>
<p>Simply, access <a target="_blank" href="https://play.kotlinlang.org/">https://play.kotlinlang.org/</a> and you can start playing around almost immediately!</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">/**
 * You can edit, run, and share this code.
 * play.kotlinlang.org
 */</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    println(<span class="hljs-string">"Hello Medium!"</span>)
}
</code></pre>
<p>As soon as the compiler is filled with the code you want to execute, find the “Run” button on the top-right corner of the UI, and wait for the result on the bottom panel. If there are any errors with the execution, the bottom panel will simply hide itself.</p>
<p><img src="https://miro.medium.com/max/1400/1*AcrlZSfF_yB4HEhk6W3GxQ.gif" alt class="image--center mx-auto" /></p>
<h6 id="heading-changing-the-settings"><strong>Changing the Settings</strong></h6>
<p>There are two main editable settings inside the Kotlin Playground. Starting at the top-left side of the screen, underneath the big Kotlin banner, you can find the Kotlin version that the Playground is currently running on. Simply clicking and choosing a different version will make sure your code is compiled and executed in a different Kotlin version.</p>
<p><img src="https://miro.medium.com/max/1400/1*CTtvOLTvM8_oMzlrpfOcMA.gif" alt class="image--center mx-auto" /></p>
<p>On the right-hand side of the Kotlin version, you can find the Target Platform that your code would be executed on. Similarly to the Kotlin version, a couple of clicks will expand the different Target Platform options and change it in order to make your code run differently.</p>
<p><img src="https://miro.medium.com/max/1400/1*k0p---X49ATSvifrC4rqeQ.gif" alt class="image--center mx-auto" /></p>
<p>Before moving on, let’s quickly go over the current options present for different Target Platforms:</p>
<ul>
<li><p><strong>JVM:</strong> Java Virtual Machine to run Kotlin in the default way</p>
</li>
<li><p><strong>JS:</strong> JavaScript for server-side development; e.g., <strong>Node.js</strong>, <strong>JQuery</strong>, <strong>React</strong>.</p>
</li>
<li><p><strong>JS IR:</strong> JavaScript Intermediate Representation is a new way for the Kotlin compiler to parse Kotlin source files</p>
</li>
<li><p><strong>JUNIT:</strong> JUnit to run test code using regular JUnit annotations like <code>@Test</code></p>
</li>
<li><p><strong>CANVAS:</strong> Introduced by <strong>HTML5</strong>, this platform allows you to draw graphics using JavaScript</p>
</li>
</ul>
<p>Last but not least, there’s also a way of adding an argument into the program execution.</p>
<p><img src="https://miro.medium.com/max/1400/1*Sm0nJ2yQ5mBthqcihO5OAw.gif" alt class="image--center mx-auto" /></p>
<p>In the example above, we’re adding the argument <code>Medium</code>. The <code>main</code> function of the code requires a small refactor in order to be able to receive and process arguments. If we run this program, we would get the following output</p>
<pre><code class="lang-kotlin">Hello, Medium!
</code></pre>
<h6 id="heading-sharing-and-embedding"><strong>Sharing and Embedding</strong></h6>
<p>The Kotlin Playground allows for a few different methods for sharing the code that is currently present in its console.</p>
<p>First, you can simply click the “Copy link” button in order to quickly share a link to the website with the current contents of the console.</p>
<p><img src="https://miro.medium.com/max/1400/1*c8YDj03thZV_36jVCxo2tg.gif" alt class="image--center mx-auto" /></p>
<p>The following panel will demonstrate how it looks when we paste the copied link into Medium.</p>
<p>Contents of link: <a target="_blank" href="https://pl.kotl.in/Eg7HMM2jR">https://pl.kotl.in/Eg7HMM2jR</a></p>
<p>Moreover, the Kotlin Playground also allows us to share our code by embedding it into a website, or any other method that supports embedding.</p>
<p>There are two main ways of embedding code from the Kotlin Playground. The first way is the default setting you see after clicking the “Share code” button, and it is meant to be added directly to HTML code.</p>
<p><img src="https://miro.medium.com/max/1400/1*Dxy6qREYdcDMLcXijGDzwA.gif" alt class="image--center mx-auto" /></p>
<p>The second way to get the content that we want to embed, is the alternative setting inside the sharing panel which is called “Medium.” This method will simply allow you to copy an address that you can then paste directly into (you guessed it) Medium or any other websites that allow for the Markup language or something of the sort.</p>
<p><img src="https://miro.medium.com/max/1400/1*nNwK6efHQGntIOxDHgx66w.gif" alt class="image--center mx-auto" /></p>
<p>In this last example we’ll show how it looks when we paste the embedding link into Medium directly, but should work for other tools using Markup too.</p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">main</span><span class="hljs-params">(args: <span class="hljs-type">Array</span>&lt;<span class="hljs-type">String</span>&gt;)</span></span> {
    println(String.format(<span class="hljs-string">"Thank you for reading, %s"</span>, args[<span class="hljs-number">0</span>]))
}
</code></pre>
<p>Contents of link: <a target="_blank" href="https://pl.kotl.in/WXIS40nvn">https://pl.kotl.in/WXIS40nvn</a></p>
<p>It should be noted that both ways of adding a preview — either by copying the link and pasting it or by embedding it directly — allow the reader to execute and edit the code directly in the panels that are shown.</p>
<p>Nevertheless, copying the link seems to truncate the view a lot more, and requires accepting the cookies agreement as a regular website would. Differently, the embedded playground instance not only gives more freedom to the sharer on how it looks, but it sports a more dynamic view that doesn’t require any cookie agreements and resizes itself as required.</p>
<h1 id="heading-how-does-it-compare-to-swift-playgrounds"><strong>How does it compare to Swift Playgrounds?</strong></h1>
<p>If there are any iOS developers still reading at this point, I know what you’re thinking: the <a target="_blank" href="https://www.apple.com/swift/playgrounds/">Swift Playgrounds</a> app has been out for some years now. I can acknowledge this, as I remember using it myself back in 2017!</p>
<p>The Kotlin Playground is not as powerful, or featureful as the Swift Playgrounds is nowadays. But the biggest advantage that the Kotlin Playground has over its adversary is that Kotlin can be run and compiled directly in the browser.</p>
<h6 id="heading-conclusion"><strong>Conclusion</strong></h6>
<p>All in all, the Kotlin Playground is fun and useful at the same time. It allows us Kotlin programmers to run small pieces of code on the fly, without the need to start up an expensive IDE. Additionally, it’s an elegant way of sharing code around, or you know, adding it into a Medium article!</p>
<p>I hope this article served as a simple introduction to this powerful and practical tool, and that you can too find its use as part of your development process. Happy coding!</p>
<p><a class="user-mention" href="https://hashnode.com/@mansivaghela">Mansi Vaghela</a> <a target="_blank" href="https://www.linkedin.com/in/mansi-droid/"><strong>LinkedIn</strong></a> <a target="_blank" href="https://twitter.com/mansi_droid"><strong>Twitter</strong></a> <a target="_blank" href="https://github.com/mansi-droid"><strong>Github</strong></a> <a target="_blank" href="https://www.youtube.com/channel/UCoGcTjvUp32To72hQVe7iZw"><strong>Youtube</strong></a></p>
]]></content:encoded></item><item><title><![CDATA[Best Way to Become Android Developer – A Complete Roadmap 2023]]></title><description><![CDATA[Android is a free and open-source operating system that runs on mobile devices such as smartphones and tablets. Further, it was developed for smartwatches and Android TV. Each of them has a specialized interface. Android is one of the most popular sm...]]></description><link>https://blog.mansi.dev/best-way-to-become-android-developer-a-complete-roadmap-2023</link><guid isPermaLink="true">https://blog.mansi.dev/best-way-to-become-android-developer-a-complete-roadmap-2023</guid><category><![CDATA[Android]]></category><category><![CDATA[android app development]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[Java]]></category><category><![CDATA[Beginner Developers]]></category><dc:creator><![CDATA[Mansi Vaghela]]></dc:creator><pubDate>Mon, 06 Feb 2023 15:13:11 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1675695495041/d4889b3a-6830-4c72-a63a-b1a5a9d9fb66.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Android is a free and open-source operating system that runs on mobile devices such as smartphones and tablets. Further, it was developed for smartwatches and Android TV. Each of them has a specialized interface. Android is one of the most popular smartphone operating systems. Android OS was developed by Android Inc., which Google bought in 2005. Various applications like games, music players, cameras, etc. are built for these smartphones and run on Android. The Google Play Store has over 3.3 million apps. Today, Android remains dominant on a global scale. Approximately 75% of the world's population prefers Android to 15% who prefer iOS. It is an operating system that has a huge market for apps.</p>
<h3 id="heading-a-roadmap-to-learn">A Roadmap to Learn</h3>
<p>Start with an overview of Android. Read some Android-related blogs and also research some Android-related things. For example, read blogs on Introduction to Android Development, History of Android, Different Versions of Android, and topics such as Why Kotlin will replace Java for Android App Development, and so on, to prepare yourself mentally for your journey on Android. Make yourself self-motivated to learn Android and build some awesome projects on it. Do it on a regular basis, and begin learning new Android concepts one at a time. It will be very helpful to join some workshops or conferences on Android before you start your journey. Make your goal clear and move on toward it.</p>
<p><strong>1) Programming Language</strong></p>
<p>Learn these programming languages before you start learning Android.</p>
<ul>
<li><p>Java</p>
</li>
<li><p>Kotlin</p>
</li>
<li><p>Sound Knowledge of XML (Extensible Markup Language)</p>
</li>
</ul>
<p><strong>2) Android Studio</strong></p>
<p>It’s better to know your tools before you are going to use it. Android Studio is the official Integrated Development Environment for Google’s Android operating system, built on JetBrains’ IntelliJ IDEA software and designed specifically for Android development.</p>
<ul>
<li><p><strong>File Structure:</strong></p>
<ul>
<li><p>AndroidManifest.xml file</p>
</li>
<li><p>Java file</p>
</li>
<li><p>Drawable file</p>
</li>
<li><p>Layout file</p>
</li>
<li><p>mipmap file</p>
</li>
<li><p>colors.xml file</p>
</li>
<li><p>strings.xml file</p>
</li>
<li><p>styles.xml file</p>
</li>
<li><p>build.gradle(Module: app) file</p>
</li>
</ul>
</li>
<li><p><strong>Android Studio Overview:</strong></p>
<ul>
<li><p>Create a new project</p>
</li>
<li><p>Reopen, close, save the project</p>
</li>
<li><p>Create a new activity, classes, drawable resource files</p>
</li>
<li><p>Run the app on AVD of Emulator or in a real device etc.</p>
</li>
</ul>
</li>
</ul>
<p><strong>3) Android Components</strong></p>
<p>There are some necessary building blocks that an Android application consists of. These loosely coupled components are bound by the application manifest file, which contains a description of each component and how they interact.</p>
<ul>
<li><p><strong>Activity:</strong></p>
<ul>
<li><p>Activity life cycle</p>
</li>
<li><p>Handle Activity State Changes</p>
</li>
<li><p>Understand Tasks and Back Stack</p>
</li>
<li><p>Processes and Application Lifecycle</p>
</li>
</ul>
</li>
<li><p><strong>Services:</strong></p>
<ul>
<li><p>Types of Android Services</p>
</li>
<li><p>The Life Cycle of Android Services</p>
</li>
</ul>
</li>
<li><p><strong>Content Provider:</strong></p>
<ul>
<li><p>Content URI</p>
</li>
<li><p>Operations in Content Provider</p>
</li>
<li><p>Working of the Content Provider</p>
</li>
<li><p>Creating a Content Provider</p>
</li>
</ul>
</li>
<li><p><strong>Broadcast Receiver:</strong></p>
<ul>
<li>Implicit Broadcast Exceptions</li>
</ul>
</li>
</ul>
<p><strong>4) Simple UI Design</strong></p>
<p>After you get an idea about the different components of Android, start exploring some simple UI design, which is given below.</p>
<ul>
<li><p><strong>Explore different layouts:</strong></p>
<ul>
<li><p>Frame</p>
</li>
<li><p>Linear</p>
</li>
<li><p>Relative</p>
</li>
<li><p>Constraint</p>
</li>
</ul>
</li>
<li><p><strong>View Elements:</strong></p>
<ul>
<li><p>TextView</p>
</li>
<li><p>EditText</p>
</li>
<li><p>Buttons</p>
</li>
<li><p>ImageView</p>
</li>
</ul>
</li>
<li><p><strong>Intent:</strong></p>
<ul>
<li><p>Implicit</p>
</li>
<li><p>Explicit</p>
</li>
<li><p>Intent Filter</p>
</li>
</ul>
</li>
</ul>
<p><strong>5) Complex UI Design</strong></p>
<p>Once you've mastered simple UI design, you can move on to more complex UI design tasks, such as:</p>
<ul>
<li><p>ListView</p>
</li>
<li><p>RecycleVIew</p>
</li>
<li><p>Fragments</p>
</li>
<li><p>Dialogs</p>
</li>
<li><p>Toast</p>
</li>
<li><p>Bottom Sheets</p>
</li>
<li><p>Navigation Drawer</p>
</li>
<li><p>Tabs</p>
</li>
<li><p>Material Design</p>
</li>
<li><p>Some inserting Animations</p>
</li>
</ul>
<p><strong>6) Storage</strong></p>
<p>In Android, there are three types of storage systems:</p>
<ul>
<li><p>Shared Preferences</p>
</li>
<li><p>File System</p>
</li>
<li><p>Database</p>
<ul>
<li>RoomDB</li>
</ul>
</li>
</ul>
<p><strong>7) Build</strong></p>
<ul>
<li><p>Gradle</p>
</li>
<li><p>Debug/ Release Configuration</p>
</li>
</ul>
<p><strong>8) Threading</strong></p>
<ul>
<li><p>Threads</p>
</li>
<li><p>Looper</p>
</li>
</ul>
<p><strong>9) Debugging</strong></p>
<p>Debugging is an essential skill for any developer. So the developer must learn these things:</p>
<ul>
<li><p>Exceptions</p>
</li>
<li><p>Error Handling</p>
</li>
<li><p>Logging</p>
</li>
<li><p>Memory Profiling</p>
</li>
</ul>
<p><strong>10) Memory Leaks</strong></p>
<ul>
<li><p>Cause of memory leaks</p>
</li>
<li><p>Detecting and fixing memory leaks</p>
</li>
<li><p>Context</p>
</li>
</ul>
<p><strong>11) Third-Party Libraries</strong></p>
<ul>
<li><p>Image Loading Libraries</p>
<ul>
<li><p>Glide</p>
</li>
<li><p>Picasso</p>
</li>
<li><p>Fresco</p>
</li>
<li><p>COIL</p>
</li>
</ul>
</li>
<li><p>Dependency Injection</p>
<ul>
<li>Dragger</li>
</ul>
</li>
<li><p>Networking</p>
<ul>
<li>Retrofit</li>
</ul>
</li>
<li><p>Multithreading</p>
<ul>
<li><p>Coroutines</p>
</li>
<li><p>Rxjava</p>
</li>
</ul>
</li>
</ul>
<p><strong>12) Android Jetpack</strong></p>
<p><strong><em>On its official site</em></strong>*, it says Android Jetpack is a set of libraries, tools, and architectural guidance to help make it quick and easy to build great Android apps. It provides common infrastructure code so you can focus on what makes your app unique.*</p>
<ul>
<li><p>AppCompat library</p>
</li>
<li><p>Architecture components,</p>
</li>
<li><p>Animation and transitions</p>
</li>
<li><p>Android Ktx</p>
</li>
<li><p>Navigation</p>
</li>
<li><p>Paging</p>
</li>
<li><p>Slices</p>
</li>
<li><p>WorkManager</p>
</li>
</ul>
<p><strong>13) Android Architecture</strong></p>
<p>The three famous architecture in the Android world are:</p>
<ul>
<li><p>MVVM (Model–View–ViewModel)</p>
</li>
<li><p>MVI (Model-View-Intent)</p>
</li>
<li><p>MVP (Model View Presenter)</p>
</li>
</ul>
<p><strong>14) Firebase</strong></p>
<ul>
<li><p>FCM (Firebase Cloud Messaging)</p>
</li>
<li><p>Analytics</p>
</li>
<li><p>Remote Config</p>
</li>
<li><p>App Indexing</p>
</li>
</ul>
<p><strong>15) Unit Testing</strong></p>
<ul>
<li><p>Local Unit Testing</p>
</li>
<li><p>Instrumentation Testing</p>
</li>
</ul>
<p><strong>16) Security</strong></p>
<ul>
<li><p>Encrypt / Decrypt</p>
</li>
<li><p>Proguard</p>
</li>
</ul>
<p><strong>17) App Release</strong></p>
<ul>
<li><p>Signed APK</p>
</li>
<li><p>Play Store</p>
</li>
</ul>
<p><strong>18) Keep Practicing and Read Some Android Tips</strong></p>
<p>“Practice makes a man perfect" which explains the importance of continuous practice in any subject to learn anything. So keep practicing and read some Android tips. Below is a complete diagrammatical representation of the Android Roadmap.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675696085439/84ff0396-e999-4fa2-a9ae-09e03af33afc.png" alt class="image--center mx-auto" /></p>
<p>More information will be available on the below official page:<br /><a target="_blank" href="https://developer.android.com/courses">https://developer.android.com/courses</a></p>
<p><a class="user-mention" href="https://hashnode.com/@mansivaghela">Mansi Vaghela</a> <a target="_blank" href="https://www.linkedin.com/in/mansi-droid/"><strong>LinkedIn</strong></a> <a target="_blank" href="https://twitter.com/mansi_droid"><strong>Twitter</strong></a> <a target="_blank" href="https://github.com/mansi-droid"><strong>Github</strong></a> <a target="_blank" href="https://www.youtube.com/channel/UCoGcTjvUp32To72hQVe7iZw"><strong>Youtube</strong></a></p>
]]></content:encoded></item><item><title><![CDATA[In-App Review Android Implementation in Kotlin]]></title><description><![CDATA[As soon as the review for the app comes to mind, you worry about going to the Playstore, correct?A review is an integral part that lets the developer know how much the users are enjoying their application. However, users generally do not review many ...]]></description><link>https://blog.mansi.dev/in-app-review-android-implementation-in-kotlin</link><guid isPermaLink="true">https://blog.mansi.dev/in-app-review-android-implementation-in-kotlin</guid><category><![CDATA[Android]]></category><category><![CDATA[android app development]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[Developer]]></category><category><![CDATA[development]]></category><dc:creator><![CDATA[Mansi Vaghela]]></dc:creator><pubDate>Sat, 04 Feb 2023 10:24:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1675506218070/0bdfcf5a-5d42-4d0a-bc34-540b45b8019d.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>As soon as the review for the app comes to mind, you worry about going to the Playstore, correct?<br />A review is an integral part that lets the developer know how much the users are enjoying their application. However, users generally do not review many apps because they do not want to go to the Play Store every time just to read a review.</p>
<p>But you, as a developer, want users to give ratings and feedback on your application.<br />So in order to solve this pain of users giving feedback from Playstore, Google developed an <a target="_blank" href="https://developer.android.com/guide/playcore/in-app-review">In-App Review API</a> for letting users give their feedback directly within the app.</p>
<p>So lets quickly jump into the coding of this. It’s very easy to implement but the testing is quite a pain if you are a new developer.</p>
<p><strong>Step 1</strong>: Add the Play core dependency in your build.gradle file.</p>
<pre><code class="lang-kotlin">implementation <span class="hljs-string">'com.google.android.play:core:1.10.3'</span>
</code></pre>
<p><strong>Step 2</strong>: Now in your Activity</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MainActivity</span>: <span class="hljs-type">AppCompatActivity</span></span>() {

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">var</span> reviewManager : ReviewManager? = <span class="hljs-literal">null</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">var</span> reviewInfo : ReviewInfo? = <span class="hljs-literal">null</span>

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onCreate</span><span class="hljs-params">(savedInstanceState : <span class="hljs-type">Bundle</span>?)</span></span> {
        <span class="hljs-keyword">super</span>.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(<span class="hljs-keyword">this</span>,                   R.layout.activity_main)
reviewManager = ReviewManagerFactory.create(<span class="hljs-keyword">this</span>)
                <span class="hljs-keyword">val</span> request : Task&lt;ReviewInfo&gt; = reviewManager!!.requestReviewFlow()
                request.addOnCompleteListener { task -&gt;
                    <span class="hljs-keyword">if</span> (task.isSuccessful) {
                        <span class="hljs-comment">// We can get the ReviewInfo object</span>
                        reviewInfo = task.result
                    } <span class="hljs-keyword">else</span> {
               <span class="hljs-comment">// There was some problem, continue regardless of the result.</span>
                    }
                }
 }
<span class="hljs-comment">// Just to test on some button click show the app review dialog.</span>
                btnClick.setOnClickListener(<span class="hljs-keyword">object</span> : OnClickListener() {
                    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onClick</span><span class="hljs-params">(v : <span class="hljs-type">View</span>?)</span></span> {
                        <span class="hljs-keyword">val</span> flow = reviewManager!!.launchReviewFlow(<span class="hljs-keyword">this</span><span class="hljs-symbol">@MainActivity</span>, reviewInfo!!)
                        flow.addOnCompleteListener { task : Task&lt;<span class="hljs-built_in">Void</span>?&gt;? -&gt; }
                    }
                })
     }
}
</code></pre>
<p><strong>Note:</strong> The <a target="_blank" href="https://developer.android.com/reference/com/google/android/play/core/review/ReviewInfo"><code>ReviewInfo</code></a> object is only valid for a limited amount of time. Your app should request a <code>ReviewInfo</code> object ahead of time (pre-cache), but only once you are certain that your app will launch the in-app review flow.</p>
<p><strong>Note:</strong> It is not suggested to show the app review dialog on a button click. Please read the guidelines <a target="_blank" href="https://developer.android.com/guide/playcore/in-app-review#when-to-request">here</a>.</p>
<p>That’s it. The coding part is completed.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675506038394/a29b3006-e22d-48a1-b826-da3b738d0639.jpeg" alt class="image--center mx-auto" /></p>
<p><strong>Key points to remember:</strong></p>
<ul>
<li><p>If you are using the Internal Sharing app to test this, you won’t be able to submit the review. The submit button is disabled in this case.</p>
</li>
<li><p>After you have successfully tested it, remove your email from the Internal App Testers list to get the actual Public Review Dialog. Otherwise, you would always get a Private Review.</p>
</li>
<li><p>The app review dialog won’t show to users who have already given the ratings on the play store. To test at your end, delete the review from the play store and it will show up.</p>
</li>
<li><p>Sometimes, dialog won’t even show up, because of the quota limit of <strong><em>launchReviewFlow</em></strong>*.* See here for more <a target="_blank" href="https://developer.android.com/guide/playcore/in-app-review#quotas">info</a>.</p>
</li>
<li><p>You should not depend on the dialog to show up and then you do your remaining work because you don't get any callback whether the user has given the feedback or not.</p>
</li>
</ul>
<p>More information will be available on the below official page:<br /><a target="_blank" href="https://developer.android.com/guide/playcore/in-app-review#when-to-request">https://developer.android.com/guide/playcore/in-app-review#when-to-request</a></p>
<p><a class="user-mention" href="https://hashnode.com/@mansivaghela">Mansi Vaghela</a> <a target="_blank" href="https://www.linkedin.com/in/mansi-droid/"><strong>LinkedIn</strong></a> <a target="_blank" href="https://twitter.com/mansi_droid"><strong>Twitter</strong></a> <a target="_blank" href="https://github.com/mansi-droid"><strong>Github</strong></a> <a target="_blank" href="https://www.youtube.com/channel/UCoGcTjvUp32To72hQVe7iZw"><strong>Youtube</strong></a></p>
]]></content:encoded></item><item><title><![CDATA[MVVM (Model View ViewModel) Architecture Pattern in Android]]></title><description><![CDATA[We’ll be discussing and implementing the Android MVVM architectural pattern in our Android application.
Why do we need these patterns?
Adding everything to a single activity or fragment would lead to problems in testing and refactoring the code. Henc...]]></description><link>https://blog.mansi.dev/mvvm-model-view-viewmodel-architecture-pattern-in-android</link><guid isPermaLink="true">https://blog.mansi.dev/mvvm-model-view-viewmodel-architecture-pattern-in-android</guid><category><![CDATA[Android]]></category><category><![CDATA[android app development]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[Developer]]></category><category><![CDATA[development]]></category><dc:creator><![CDATA[Mansi Vaghela]]></dc:creator><pubDate>Sat, 04 Feb 2023 09:31:56 GMT</pubDate><content:encoded><![CDATA[<p>We’ll be discussing and implementing the Android MVVM architectural pattern in our Android application.</p>
<p><strong>Why do we need these patterns?</strong></p>
<p>Adding everything to a single activity or fragment would lead to problems in testing and refactoring the code. Hence, the use of separation of code and clean architecture is recommended.</p>
<p><strong>Model—View—ViewModel (MVVM)</strong> is the industry-recognized software <a target="_blank" href="https://www.geeksforgeeks.org/android-architecture-patterns/"><strong>architecture pattern</strong></a> that overcomes all the drawbacks of MVP and <a target="_blank" href="https://www.geeksforgeeks.org/mvc-model-view-controller-architecture-pattern-in-android-with-example/"><strong>MVC</strong></a> design patterns. MVVM suggests separating the data presentation logic (views or UI) from the core business logic part of the application.</p>
<h4 id="heading-the-separate-code-layers-of-mvvm-are"><strong>The separate code layers of MVVM are:</strong></h4>
<ul>
<li><p><strong>Model</strong>: This holds the data of the application. It cannot directly talk to the View. Generally, it’s recommended to expose the data to the ViewModel through Observables.</p>
</li>
<li><p><strong>View</strong>: It represents the UI of the application devoid of any Application Logic. It observes the ViewModel.</p>
</li>
<li><p><strong>ViewModel</strong>: It acts as a link between the Model and the View. It’s responsible for transforming the data from the Model. It provides data streams to the View. It also uses hooks or callbacks to update the View. It’ll ask for the data from the Model.</p>
</li>
</ul>
<p>The following flow illustrates the core MVVM pattern.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675501365972/14f471da-d756-4f81-be02-1c28f975e3fe.png" alt class="image--center mx-auto" /></p>
<p>The MVVM pattern has some similarities with the MVP (Model—View—Presenter) design pattern, as the presenter role is played by ViewModel. However, the drawbacks of the MVP pattern have been solved by MVVM in the following ways:</p>
<ul>
<li><p>ViewModel does not hold any kind of reference to the View.</p>
</li>
<li><p>Many to-1 relationships exist between View and ViewModel.</p>
</li>
<li><p>No triggering methods to update the View.</p>
</li>
</ul>
<p>There are two ways to implement MVVM in Android:</p>
<ul>
<li><p>Data Binding</p>
</li>
<li><p>RXJava</p>
</li>
</ul>
<p>Here, we’ll be using data binding only. Google introduced the Data Binding Library in order to bind data directly in the XML layout. We’ll be creating a simple login page example application that asks for user inputs. We’ll see how the ViewModel notifies the View when to show a toast message without keeping a reference to the View.</p>
<p><strong>How is it possible to notify a class without having a reference to it?</strong> It can be done in three different ways:</p>
<ul>
<li><p>Using Two Way Data Binding</p>
</li>
<li><p>Using Live Data</p>
</li>
<li><p>Using RxJava</p>
</li>
</ul>
<h3 id="heading-two-way-data-binding">Two Way Data Binding</h3>
<p>Two-way Data Binding is a technique of binding your objects to your XML layouts such that the Object and the layout can both send data to each other. In our case, the ViewModel can send data to the layout and also observe changes. For this, we need a <code>BindingAdapter</code> and custom attribute defined in the XML. The binding adapter would listen to changes in the attribute property. This point can be visualized by the example in this tutorial.</p>
<blockquote>
<p><em>Syntax for the two way data binding is</em> <strong><em>@={variable}</em></strong></p>
</blockquote>
<h3 id="heading-adding-the-data-binding-library">Adding the Data Binding Library</h3>
<p>Add the following code to your app’s build.gradle file:</p>
<pre><code class="lang-kotlin">android {
    dataBinding {
        enabled = <span class="hljs-literal">true</span>
    }
}
</code></pre>
<p>This enables data binding in your application.</p>
<h3 id="heading-adding-the-dependencies">Adding the Dependencies</h3>
<p>Add the following dependencies to your <code>build.gradle</code> file :</p>
<pre><code class="lang-kotlin">implementation <span class="hljs-string">'android.arch.lifecycle:extensions:1.1.1'</span>
</code></pre>
<h3 id="heading-data-class">Data Class</h3>
<p>The data class would hold the user’s email and password. The following <a target="_blank" href="http://User.java">User.</a>kt class does it:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">package</span> com.dev.androidmvvmbasics.model

<span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span></span>(
    <span class="hljs-keyword">var</span> email: String,
    <span class="hljs-keyword">var</span> password: String
)
</code></pre>
<p>Two-way Data Binding allows us to bind objects in the XML layouts such that the object can send data to the layout, and vice versa. The Syntax for two way data binding is <code>@={variable}</code></p>
<h3 id="heading-layout">Layout</h3>
<p>The code for the activity_main.xml is given below:</p>
<pre><code class="lang-kotlin">&lt;?xml version=<span class="hljs-string">"1.0"</span> encoding=<span class="hljs-string">"utf-8"</span>?&gt;
&lt;layout xmlns:android=<span class="hljs-string">"https://schemas.android.com/apk/res/android"</span>
    xmlns:bind=<span class="hljs-string">"https://schemas.android.com/tools"</span>&gt;

    &lt;<span class="hljs-keyword">data</span>&gt;

        &lt;variable
            name=<span class="hljs-string">"viewModel"</span>
            type=<span class="hljs-string">"com.dev.androidmvvmbasics.viewmodels.LoginViewModel"</span> /&gt;
    &lt;/<span class="hljs-keyword">data</span>&gt;


    &lt;androidx.core.widget.NestedScrollView
        android:layout_width=<span class="hljs-string">"match_parent"</span>
        android:layout_height=<span class="hljs-string">"match_parent"</span>&gt;

        &lt;LinearLayout
            android:layout_width=<span class="hljs-string">"match_parent"</span>
            android:layout_height=<span class="hljs-string">"wrap_content"</span>
            android:layout_gravity=<span class="hljs-string">"center"</span>
            android:layout_margin=<span class="hljs-string">"8dp"</span>
            android:orientation=<span class="hljs-string">"vertical"</span>&gt;

            &lt;EditText
                android:id=<span class="hljs-string">"@+id/etEmail"</span>
                android:layout_width=<span class="hljs-string">"match_parent"</span>
                android:layout_height=<span class="hljs-string">"wrap_content"</span>
                android:hint=<span class="hljs-string">"Email"</span>
                android:inputType=<span class="hljs-string">"textEmailAddress"</span>
                android:padding=<span class="hljs-string">"8dp"</span>
                android:text=<span class="hljs-string">"@={viewModel.userEmail}"</span> /&gt;

            &lt;EditText
                android:id=<span class="hljs-string">"@+id/etPassword"</span>
                android:layout_width=<span class="hljs-string">"match_parent"</span>
                android:layout_height=<span class="hljs-string">"wrap_content"</span>
                android:hint=<span class="hljs-string">"Password"</span>
                android:inputType=<span class="hljs-string">"textPassword"</span>
                android:padding=<span class="hljs-string">"8dp"</span>
                android:text=<span class="hljs-string">"@={viewModel.userPassword}"</span> /&gt;


            &lt;Button
                android:layout_width=<span class="hljs-string">"match_parent"</span>
                android:layout_height=<span class="hljs-string">"wrap_content"</span>
                android:layout_marginTop=<span class="hljs-string">"8dp"</span>
                android:onClick=<span class="hljs-string">"@{()-&gt; viewModel.onLoginClicked()}"</span>
                android:text=<span class="hljs-string">"LOGIN"</span>
                bind:toastMessage=<span class="hljs-string">"@{viewModel.toastMessage}"</span> /&gt;
        &lt;/LinearLayout&gt;
    &lt;/androidx.core.widget.NestedScrollView&gt;
&lt;/layout&gt;
</code></pre>
<p>Data Binding requires us to set the layout tag at the top. Here our ViewModel binds the data to the View. <code>()-&gt; viewModel.onLoginClicked()</code> invokes the Button click listener lambda defined in our ViewModel. The EditText updates the values in the Model (via View Model). <code>bind:toastMessage="@{viewModel.toastMessage}"</code> is a custom attribute we’ve created for two-way data binding. Based on changes in the toastMessage in the ViewModel the BindingAdapter would get triggered in the View.</p>
<h3 id="heading-viewmodel">ViewModel</h3>
<p>The code for the <a target="_blank" href="http://LoginViewModel.java">LoginViewModel.</a>kt is given below:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">package</span> com.dev.androidmvvmbasics.viewmodels

<span class="hljs-keyword">import</span> android.databinding.BaseObservable
<span class="hljs-keyword">import</span> android.databinding.Bindable
<span class="hljs-keyword">import</span> android.text.TextUtils
<span class="hljs-keyword">import</span> android.util.Patterns

<span class="hljs-keyword">import</span> com.android.databinding.library.baseAdapters.BR
<span class="hljs-keyword">import</span> com.dev.androidmvvmbasics.model.User

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LoginViewModel</span> : <span class="hljs-type">BaseObservable</span></span>() {
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> user : User
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> successMessage = <span class="hljs-string">"Login was successful"</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> errorMessage = <span class="hljs-string">"Email or Password not valid"</span>
    <span class="hljs-meta">@Bindable</span> <span class="hljs-keyword">var</span> toastMessage : String? = <span class="hljs-literal">null</span>
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">set</span>

    <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">setToastMessage</span><span class="hljs-params">(toastMessage : <span class="hljs-type">String</span>)</span></span> {
        <span class="hljs-keyword">this</span>.toastMessage = toastMessage
        notifyPropertyChanged(BR.toastMessage)
    }

    <span class="hljs-meta">@get:Bindable</span> <span class="hljs-keyword">var</span> userEmail : String?
        <span class="hljs-keyword">get</span>() = user.getEmail()
        <span class="hljs-keyword">set</span>(email) {
            user.setEmail(email)
            notifyPropertyChanged(BR.userEmail)
        }
    <span class="hljs-meta">@get:Bindable</span> <span class="hljs-keyword">var</span> userPassword : String?
        <span class="hljs-keyword">get</span>() = user.getPassword()
        <span class="hljs-keyword">set</span>(password) {
            user.setPassword(password)
            notifyPropertyChanged(BR.userPassword)
        }

    <span class="hljs-keyword">init</span> {
        user = User(<span class="hljs-string">""</span>, <span class="hljs-string">""</span>)
    }

    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onLoginClicked</span><span class="hljs-params">()</span></span> {
        <span class="hljs-keyword">if</span> (isInputDataValid) setToastMessage(successMessage) <span class="hljs-keyword">else</span> setToastMessage(errorMessage)
    }

    <span class="hljs-keyword">val</span> isInputDataValid : <span class="hljs-built_in">Boolean</span>
        <span class="hljs-keyword">get</span>() = !TextUtils.isEmpty(userEmail) &amp;&amp; Patterns.EMAIL_ADDRESS.matcher(userEmail)
                .matches() &amp;&amp; userPassword!!.length &gt; <span class="hljs-number">5</span>
}
</code></pre>
<p>The methods called for in the layout are implemented in the above code with the same signature. If the XML counterpart of the method doesn’t exist, we need to change the attribute to <code>app:</code>. The above class can also extend ViewModel. But we need BaseObservable since it converts the data into streams and notifies us when the <code>toastMessage</code> property is changed. We need to define the getter and setter for the toastMessage custom attribute defined in the XML. Inside the setter, we notify the observer (which will be the view in our application) that the data has changed. The view (our activity) can define the appropriate action.</p>
<p>BR class is auto-generated from data binding when you rebuild the project</p>
<p>The code for the <a target="_blank" href="http://MainActivity.java"><code>MainActivity.</code></a><code>kt</code> class is given below:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">package</span> com.dev.androidmvvmbasics.views

<span class="hljs-keyword">import</span> android.databinding.BindingAdapter
<span class="hljs-keyword">import</span> android.databinding.DataBindingUtil
<span class="hljs-keyword">import</span> android.support.v7.app.AppCompatActivity
<span class="hljs-keyword">import</span> android.os.Bundle
<span class="hljs-keyword">import</span> android.view.View
<span class="hljs-keyword">import</span> android.widget.Toast
<span class="hljs-keyword">import</span> com.dev.androidmvvmbasics.R
<span class="hljs-keyword">import</span> com.dev.androidmvvmbasics.databinding.ActivityMainBinding
<span class="hljs-keyword">import</span> com.dev.androidmvvmbasics.viewmodels.LoginViewModel


<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MainActivity</span> : <span class="hljs-type">AppCompatActivity</span></span>() {
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onCreate</span><span class="hljs-params">(savedInstanceState : <span class="hljs-type">Bundle</span>?)</span></span> {
        <span class="hljs-keyword">super</span>.onCreate(savedInstanceState)
        <span class="hljs-keyword">val</span> activityMainBinding : ActivityMainBinding = DataBindingUtil.setContentView(<span class="hljs-keyword">this</span>, R.layout.activity_main)
        activityMainBinding.setViewModel(LoginViewModel())
        activityMainBinding.executePendingBindings()
    }

    <span class="hljs-keyword">companion</span> <span class="hljs-keyword">object</span> {
        <span class="hljs-meta">@BindingAdapter(<span class="hljs-meta-string">"toastMessage"</span>)</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">runMe</span><span class="hljs-params">(view : <span class="hljs-type">View</span>, message : <span class="hljs-type">String</span>?)</span></span> {
            <span class="hljs-keyword">if</span> (message != <span class="hljs-literal">null</span>) Toast.makeText(view.getContext(), message, Toast.LENGTH_SHORT)
                    .show()
        }
    }
}
</code></pre>
<p>Thanks to DataBinding, the <code>ActivityMainBinding</code> class is auto-generated from the layout. The <code>@BindingAdapter</code> method gets triggered whenever the toastMessage attribute defined on the Button is changed. It must use the same attribute as defined in the XML and in the ViewModel. So in the above application, the ViewModel updates the Model by listening to the changes in the View. Also, the Model can update the view via the ViewModel using the <code>notifyPropertyChanged</code>.</p>
<p>More information will be available on the below official page:<br /><a target="_blank" href="https://developer.android.com/topic/architecture"><strong>https://developer.chrome.com/multidevice/android/customtabs</strong></a></p>
<p><a class="user-mention" href="https://hashnode.com/@mansivaghela">Mansi Vaghela</a> <a target="_blank" href="https://www.linkedin.com/in/mansi-droid/"><strong>LinkedIn</strong></a> <a target="_blank" href="https://twitter.com/mansi_droid"><strong>Twitter</strong></a> <a target="_blank" href="https://github.com/mansi-droid"><strong>Github</strong></a> <a target="_blank" href="https://www.youtube.com/channel/UCoGcTjvUp32To72hQVe7iZw"><strong>Youtube</strong></a></p>
]]></content:encoded></item><item><title><![CDATA[Chrome Custom Tabs in Android using Kotlin]]></title><description><![CDATA[Chrome custom tabs give apps more control over their web experience. CustomTabs is a Chrome platform component.
Chrome Custom Tabs are now generally available to all users of Chrome, on all of Chrome’s supported Android versions (Jellybean onwards).
...]]></description><link>https://blog.mansi.dev/chrome-custom-tabs-in-android-using-kotlin</link><guid isPermaLink="true">https://blog.mansi.dev/chrome-custom-tabs-in-android-using-kotlin</guid><category><![CDATA[Android]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[Developer]]></category><category><![CDATA[android app development]]></category><category><![CDATA[development]]></category><dc:creator><![CDATA[Mansi Vaghela]]></dc:creator><pubDate>Fri, 03 Feb 2023 19:45:30 GMT</pubDate><content:encoded><![CDATA[<p>Chrome custom tabs give apps more control over their web experience. CustomTabs is a Chrome platform component.</p>
<p>Chrome Custom Tabs are now generally available to all users of Chrome, on all of Chrome’s supported Android versions (Jellybean onwards).</p>
<p>Chrome Custom Tabs allow an app to customize how Chrome looks and feels. An app can change things like:</p>
<ul>
<li><p>Toolbar color</p>
</li>
<li><p>Enter and exit animations</p>
</li>
<li><p>Add custom actions to the Chrome toolbar, overflow menu and bottom toolbar</p>
</li>
</ul>
<p>Launching links in custom tabs is faster than Chrome and WebView.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675452689553/ba90f34c-3567-4904-bee1-3c414e13f924.webp" alt class="image--center mx-auto" /></p>
<p><strong>Implementation:</strong><br />First, add a custom tab library to the <em>build.gradle</em> file.</p>
<pre><code class="lang-kotlin">dependencies { 

        … 
        implementation <span class="hljs-string">'androidx.browser:browser:1.3.0'</span>

}
</code></pre>
<p>Then, start url with custom tabs in your code</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> url = <span class="hljs-string">"https://hashnode.com/@mansivaghela"</span>                         
<span class="hljs-keyword">val</span> builder = CustomTabsIntent.Builder()
<span class="hljs-keyword">var</span> customTabsIntent :CustomTabsIntent  = builder.build();
customTabsIntent.launchUrl(requireContext(), Uri.parse(url))
</code></pre>
<p>after this you can customize tabs based on your needs.</p>
<p>More information will be available in below official Chrome page:<br /><a target="_blank" href="https://developer.chrome.com/multidevice/android/customtabs">https://developer.chrome.com/multidevice/android/customtabs</a></p>
<p><a class="user-mention" href="https://hashnode.com/@mansivaghela">Mansi Vaghela</a> <a target="_blank" href="https://www.linkedin.com/in/mansi-droid/"><strong>LinkedIn</strong></a> <a target="_blank" href="https://twitter.com/mansi_droid"><strong>Twitter</strong></a> <a target="_blank" href="https://github.com/mansi-droid"><strong>Github</strong></a> <a target="_blank" href="https://www.youtube.com/channel/UCoGcTjvUp32To72hQVe7iZw"><strong>Youtube</strong></a></p>
]]></content:encoded></item><item><title><![CDATA[Kotlin Variables]]></title><description><![CDATA[A variable refers to a memory location that stores some data.You can declare variables in Kotlin using the val and var keywords.
val:A variable declared with the val keyword is read-only (immutable). It cannot be reassigned after it is initialized.
v...]]></description><link>https://blog.mansi.dev/kotlin-variables</link><guid isPermaLink="true">https://blog.mansi.dev/kotlin-variables</guid><category><![CDATA[Kotlin]]></category><category><![CDATA[Android]]></category><category><![CDATA[Developer]]></category><category><![CDATA[software development]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Mansi Vaghela]]></dc:creator><pubDate>Thu, 02 Feb 2023 10:28:47 GMT</pubDate><content:encoded><![CDATA[<p>A variable refers to a memory location that stores some data.<br />You can declare variables in Kotlin using the <strong>val</strong> and <strong>var</strong> keywords.</p>
<p><strong>val:</strong><br />A variable declared with the val keyword is read-only (immutable). It cannot be reassigned after it is initialized.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> name = <span class="hljs-string">"Kotlin"</span>
name = <span class="hljs-string">"Language"</span> <span class="hljs-comment">//Error: val can not be reassigned</span>
</code></pre>
<p>It is similar to the <em>final</em> variable in Java.</p>
<p><strong>var:</strong><br />Variable declared using var keyword is mutable. It can be reassigned after it is initialized.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> name = <span class="hljs-string">"Kotlin"</span>
name = <span class="hljs-string">"Language"</span> <span class="hljs-comment">//No error. It works</span>
</code></pre>
<p>It is similar to regular variable in Java.</p>
<p><strong>Type inference:</strong><br />In Kotlin, it is not mandatory to explicitly specify the type of variable that you declare. The Kotlin compiler will automatically infer the type of the variable from the initialized section.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> name = <span class="hljs-string">"Kotlin"</span> <span class="hljs-comment">// type infered as "String"</span>
<span class="hljs-keyword">val</span> value = <span class="hljs-number">100</span> <span class="hljs-comment">//type infered as "Int"</span>
</code></pre>
<p>You can also explicitly define the type of the variable.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> name: String = <span class="hljs-string">"Kotlin"</span>
<span class="hljs-keyword">val</span> value: <span class="hljs-built_in">Int</span> = <span class="hljs-number">100</span>
</code></pre>
<p>Type of the variable declaration mandatory if you dont initialize the variable.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> name <span class="hljs-comment">// Error: variable must either have a Type annotation or be initialized</span>
name = <span class="hljs-string">"Kotlin"</span>
</code></pre>
<p>You can also declare something like this.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> name: String <span class="hljs-comment">//works</span>
name = <span class="hljs-string">"Kotlin"</span>
</code></pre>
<p><a class="user-mention" href="https://hashnode.com/@mansivaghela">Mansi Vaghela</a> <a target="_blank" href="https://www.linkedin.com/in/mansi-droid/"><strong>LinkedIn</strong></a> <a target="_blank" href="https://twitter.com/mansi_droid"><strong>Twitter</strong></a> <a target="_blank" href="https://github.com/mansi-droid"><strong>Github</strong></a> <a target="_blank" href="https://www.youtube.com/channel/UCoGcTjvUp32To72hQVe7iZw"><strong>Youtube</strong></a></p>
]]></content:encoded></item><item><title><![CDATA[Comparison Kotlin to Java Programming Language]]></title><description><![CDATA[Kotlin fixes some of the Java issues.

Null references are controlled by the type system.

No raw types

Arrays in Kotlin are invariant

Kotlin has proper function types, as opposed to Java’s SAM-conversions

Use-site variance without wildcards

Kotl...]]></description><link>https://blog.mansi.dev/comparison-kotlin-to-java-programming-language</link><guid isPermaLink="true">https://blog.mansi.dev/comparison-kotlin-to-java-programming-language</guid><category><![CDATA[Kotlin]]></category><category><![CDATA[Java]]></category><category><![CDATA[kotlin beginner]]></category><category><![CDATA[Developer]]></category><category><![CDATA[development]]></category><dc:creator><![CDATA[Mansi Vaghela]]></dc:creator><pubDate>Thu, 02 Feb 2023 10:24:13 GMT</pubDate><content:encoded><![CDATA[<p>Kotlin fixes some of the Java issues.</p>
<ul>
<li><p>Null references are controlled by the type system.</p>
</li>
<li><p>No raw types</p>
</li>
<li><p>Arrays in Kotlin are invariant</p>
</li>
<li><p>Kotlin has proper function types, as opposed to Java’s SAM-conversions</p>
</li>
<li><p>Use-site variance without wildcards</p>
</li>
<li><p>Kotlin does not have checked exceptions</p>
</li>
</ul>
<p>Java has below that kotlin does not have</p>
<ul>
<li><p>Checked exceptions</p>
</li>
<li><p>Primitive types that are not classes</p>
</li>
<li><p>Static members</p>
</li>
<li><p>Non-private fields</p>
</li>
<li><p>Wildcard-types</p>
</li>
<li><p>Ternary-operator a ? b : c</p>
</li>
</ul>
<p>What Kotlin has that Java does not</p>
<ul>
<li><p>Lambda expressions + Inline functions</p>
</li>
<li><p>Extension functions</p>
</li>
<li><p>Null-safety</p>
</li>
<li><p>Smart casts</p>
</li>
<li><p>String templates</p>
</li>
<li><p>Properties</p>
</li>
<li><p>Primary constructors</p>
</li>
<li><p>First-class delegation</p>
</li>
<li><p>Type inference for variable and property types</p>
</li>
<li><p>Singletons</p>
</li>
<li><p>Declaration-site variance &amp; Type projections</p>
</li>
<li><p>Range expressions</p>
</li>
<li><p>Operator overloading</p>
</li>
<li><p>Companion objects</p>
</li>
<li><p>Data classes</p>
</li>
<li><p>Separate interfaces for read-only and mutable collections</p>
</li>
<li><p>Coroutines</p>
</li>
</ul>
<p><a class="user-mention" href="https://hashnode.com/@mansivaghela">Mansi Vaghela</a> <a target="_blank" href="https://www.linkedin.com/in/mansi-droid/"><strong>LinkedIn</strong></a> <a target="_blank" href="https://twitter.com/mansi_droid"><strong>Twitter</strong></a> <a target="_blank" href="https://github.com/mansi-droid"><strong>Github</strong></a> <a target="_blank" href="https://www.youtube.com/channel/UCoGcTjvUp32To72hQVe7iZw"><strong>Youtube</strong></a></p>
]]></content:encoded></item><item><title><![CDATA[SOLID Design Principles In Kotlin]]></title><description><![CDATA[In this article, we will figure out what exactly SOLID principles are and, most importantly, we will check out a few Kotlin examples to get an even better understanding. SOLID is an acronym for five design principles in Object-Oriented software devel...]]></description><link>https://blog.mansi.dev/solid-design-principles-in-kotlin</link><guid isPermaLink="true">https://blog.mansi.dev/solid-design-principles-in-kotlin</guid><category><![CDATA[developers]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[design principles]]></category><category><![CDATA[SOLID principles]]></category><category><![CDATA[software development]]></category><dc:creator><![CDATA[Mansi Vaghela]]></dc:creator><pubDate>Thu, 02 Feb 2023 10:18:29 GMT</pubDate><content:encoded><![CDATA[<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675332936759/87440303-9153-4e8a-b0e4-e3571751a7be.png" alt class="image--center mx-auto" /></p>
<p>In this article, we will figure out what exactly <strong>SOLID principles</strong> are and, most importantly, we will check out a few <strong>Kotlin examples</strong> to get an even better understanding. SOLID is an acronym for five design principles in Object-Oriented software development intended to make software designs more understandable, flexible and maintainable. These five principles are described by Robert C. Martin.</p>
<p>SOLID principles are briefly as follows:</p>
<ul>
<li><p><strong>S</strong> — Single Responsibility Principle (known as SRP)</p>
</li>
<li><p><strong>O</strong> — Open/Closed Principle</p>
</li>
<li><p><strong>L</strong> — Liskov’s Substitution Principle</p>
</li>
<li><p><strong>I</strong> — Interface Segregation Principle</p>
</li>
<li><p><strong>D</strong> — Dependency Inversion Principle</p>
</li>
</ul>
<h2 id="heading-1-single-responsibility-principle"><strong>1. Single-Responsibility Principle</strong></h2>
<p>The single-responsibility principle states:</p>
<blockquote>
<p><em>A class should have only one reason to change.</em></p>
</blockquote>
<p>The Single Responsibility Principle indicates that every class should have one and only one responsibility. In other words, if our class does more than one responsibility, we should split the functionalities and responsibilities in various classes. Therefore, this makes the class more robust.</p>
<p>With all of that in mind, let’s see the following example:</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span></span>(
  <span class="hljs-keyword">val</span> id: <span class="hljs-built_in">Int</span>,
  <span class="hljs-keyword">val</span> name: String,
  <span class="hljs-keyword">val</span> email: String,
  <span class="hljs-keyword">val</span> phoneNumber: String
)
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AdminDashboardService</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">sendNotification</span><span class="hljs-params">(user: <span class="hljs-type">User</span>)</span></span> {
    println(<span class="hljs-string">"Preparing email content"</span>)
    println(<span class="hljs-string">"Sending email to <span class="hljs-subst">${user.email}</span>"</span>)
  }
  <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">deleteUser</span><span class="hljs-params">(user: <span class="hljs-type">User</span>)</span></span> {
    println(<span class="hljs-string">"Deleting user with id <span class="hljs-subst">${user.id}</span> from the database"</span>)
  }
}
</code></pre>
<p>For the purpose of simplicity, the above functions are just printing some text to the output. Nevertheless, in the real-life scenarios the <em>sendNotification()</em> would be responsible for preparing an HTML content for the email and sending it to the given email address. On the other hand, the <em>deleteUser()</em> would perform an SQL query deleting the record from connected database.</p>
<p>In such a case, we can clearly see that our service is responsible for <strong>three different things</strong>. Moreover, let’s imagine that:</p>
<ul>
<li><p>the marketing team requested a change in the e-mail template because of the branding change</p>
</li>
<li><p>the CTO requested an email automation provider change</p>
</li>
<li><p>the data team requested a change in SQL query</p>
</li>
</ul>
<p>We can clearly see that each of these requests may easily affect theoretically unrelated business functions.</p>
<p>As the next step, let’s see how the refactored code could look like:</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserAccountService</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">deleteUser</span><span class="hljs-params">(user: <span class="hljs-type">User</span>)</span></span> {
    println(<span class="hljs-string">"Deleting user with id <span class="hljs-subst">${user.id}</span> from the database"</span>)
  }
}
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">EmailContentProvider</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">prepareContent</span><span class="hljs-params">()</span></span> {
    println(<span class="hljs-string">"Preparing email content"</span>)
  }
}
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">EmailNotificationService</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">sendNotification</span><span class="hljs-params">(user: <span class="hljs-type">User</span>)</span></span> {
     println(<span class="hljs-string">"Sending email to <span class="hljs-subst">${user.email}</span>"</span>)
  }
}
</code></pre>
<p>This time, we can clearly see that each class is responsible for exactly one thing (has one reason to change).</p>
<p><strong>Benefits</strong></p>
<ul>
<li><p>most importantly- any bug introduced to the particular class <strong>affects less parts of the system</strong> (and organization as a whole)</p>
</li>
<li><p>additionally, the number of <strong>merge conflicts</strong> is reduced when multiple people are working with the codebase</p>
</li>
<li><p>whatsoever, it can introduce much better <strong>readability</strong> than the monolithic classes</p>
</li>
</ul>
<h1 id="heading-2-o-openclosed-principle"><strong>2. O — Open/Closed Principle</strong></h1>
<p>As the next step, let’s take a look at the <strong>open-closed principle:</strong></p>
<blockquote>
<p><em>Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.</em></p>
</blockquote>
<p>The Open/Closed principle states “software entities such as classes, components, and modules should be open for extension but closed for modification." That is, such an entity can allow its behavior to be extended without modifying its source code.</p>
<p>Let’s imagine that we were asked to implement a logging feature for custom header objects. However, the logger itself should avoid printing the values of particular headers: <em>header-one</em> and <em>header-two,</em> as they contain vulnerable data.</p>
<p>Given these requirements, we’ve decided to put the excluded headers inside the companion object and expose a <em>log()</em> function, which will make sure that we won’t log any vulnerable data:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Header</span></span>(
  <span class="hljs-keyword">val</span> name: String,
  <span class="hljs-keyword">val</span> value: String
)
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HeadersLogger</span> </span>{
  <span class="hljs-keyword">companion</span> <span class="hljs-keyword">object</span> {
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> forbiddenHeaders = setOf(<span class="hljs-string">"header-one"</span>, <span class="hljs-string">"header-two"</span>)
  }
  <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">log</span><span class="hljs-params">(header: <span class="hljs-type">Header</span>)</span></span> {
    <span class="hljs-keyword">if</span> (!forbiddenHeaders.contains(header.name))
      println(header.value)
  }
}
</code></pre>
<p>Everything works perfectly, but what if at some point the client asks us to exclude additional headers?</p>
<p>Given the above code, we have no other option, than to either modify the <em>HeadersLogger</em> class to contain the additional header or implement a new one. Definitely, the above code is <strong>neither open for extension nor closed for modification</strong>.</p>
<p>How could we change the above code to follow the above principle? Well, let’s see the following snippet:</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HeadersLogger</span></span>(<span class="hljs-keyword">val</span> forbiddenHeaders: Set&lt;String&gt; = setOf()) {
  <span class="hljs-keyword">companion</span> <span class="hljs-keyword">object</span> {
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> forbiddenHeaders = setOf(<span class="hljs-string">"header-one"</span>, <span class="hljs-string">"header-two"</span>)
  }
  <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">log</span><span class="hljs-params">(header: <span class="hljs-type">Header</span>)</span></span> {
    <span class="hljs-keyword">val</span> headerName = header.name
      <span class="hljs-keyword">if</span> (!forbiddenHeaders.contains(headerName)
        &amp;&amp; !additionalForbiddenHeaders.contains(headerName)
      )
        println(header.value)
  }
}
</code></pre>
<p>As we can see, such a small change gives us much more flexibility. Although we’ve predefined two headers, which should be always skipped, we can easily add new without modification of the existing class. Furthermore, we can extract this code as a common dependency and reuse it in multiple parts of the system.</p>
<p><strong>Benefits</strong></p>
<ul>
<li><p>first of all, <strong>reusability</strong> and <strong>flexibility</strong>. We can use already existing codebase to implement new features or apply changes without the need of reinventing the wheel</p>
</li>
<li><p>moreover, the above advantage is a great <strong>time-saver</strong></p>
</li>
<li><p>additionally, modification of existing classes might introduce unwanted behavior everywhere they’ve been used. With the open-closed principle, we can easily <strong>avoid this risk</strong></p>
</li>
</ul>
<h1 id="heading-3-liskov-substitution-principle"><strong>3. L</strong>iskov substitution principle</h1>
<p>Next, let’s check the definition of the <strong>Liskov substitution principle:</strong></p>
<blockquote>
<p><em>Let Φ(x) be a property provable about objects x of type T. Then Φ(y) should be true for objects y of type S where S is a subtype of T.</em></p>
</blockquote>
<p>This principle indicates that parent classes should be easily substituted with their child classes without changing the behavior of software. It means that a sub-class should override the methods from a parent class, which does not break the functionality of the parent class.</p>
<p>Let’s say that we’ve got two types of users in the app: standard and admin. Both types of the account can be created. Nevertheless, the admin account can not be deleted in our app (for instance it can be done only from an external one).</p>
<p>Given that, let’s have a look at the example:</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Managable</span></span>{
  <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">create</span><span class="hljs-params">()</span></span>
  <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">delete</span><span class="hljs-params">()</span></span>
}
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">StandardUser</span> : <span class="hljs-type">Managable{</span></span>
  <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">create</span><span class="hljs-params">()</span></span> {
    println(<span class="hljs-string">"Creating Standard User account"</span>)
  }
  <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">delete</span><span class="hljs-params">()</span></span> {
    println(<span class="hljs-string">"Deleting Standard User account"</span>)
  }
}
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AdminUser</span> : <span class="hljs-type">Managable{</span></span>
  <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">create</span><span class="hljs-params">()</span></span> {
    println(<span class="hljs-string">"Creating Admin User account"</span>)
  }
  <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">delete</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">throw</span> RuntimeException(<span class="hljs-string">"Admin Account can not be deleted!"</span>)
  }
}
</code></pre>
<p>At first glance, everything seems to be working, as expected. The interface methods has been overriden and we can compile it successfully. Additionally, we’ve applied the requirements and the <em>delete()</em> implementation prohibits from deleting the Admin account.</p>
<p>Nevertheless, we can clearly spot, that <strong>replacement of the interface invocation with the derived method will definitely break the flow</strong>. Let’s imagine that someone else wrote a generic test for Managable interface. Given the contract, tester assumed that invoking the <em>delete()</em> should remove the data from the external database regardless of the user type. Unfortunately, that’s not the case here and the test will work as expected with the StandardUser instance and fail with the exception for the AdminUser.</p>
<p>There are plenty of possibilities when it comes to the above code. Let’s see the example one:</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Creatable</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">create</span><span class="hljs-params">()</span></span>
}
<span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Deletable</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">delete</span><span class="hljs-params">()</span></span>
}
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">StandardUser</span> : <span class="hljs-type">Creatable</span>, <span class="hljs-type">Deletable {</span></span>
  <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">create</span><span class="hljs-params">()</span></span> {
    println(<span class="hljs-string">"Creating Standard User account"</span>)
  }
  <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">delete</span><span class="hljs-params">()</span></span> {
    println(<span class="hljs-string">"Deleting Standard User account"</span>)
  }
}
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AdminUser</span> : <span class="hljs-type">Creatable {</span></span>
  <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">create</span><span class="hljs-params">()</span></span> {
    println(<span class="hljs-string">"Creating Admin User account"</span>)
  }
}
</code></pre>
<p>This time, we’ve introduced a more specific contract with two, separate interfaces. Definitely, the hypothetical substitution <strong>won’t break the flow</strong>.</p>
<p><strong>Benefits</strong></p>
<ul>
<li><p>when our subtypes conform behaviorally to the supertypes in our code, our <strong>code hierarchy becomes cleaner</strong></p>
</li>
<li><p>furthermore, people working with the abstraction (interface in our case) can be sure that <strong>no unexpected behavior occurs</strong></p>
</li>
</ul>
<h1 id="heading-4-interface-segregation-principle"><strong>4. I</strong>nterface segregation principle</h1>
<p>We've already covered three rules, so it’s time to check the <strong>interface segregation principle:</strong></p>
<blockquote>
<p><em>Many client-specific interfaces are better than one general-purpose interface.</em></p>
</blockquote>
<p>The interface-segregation principle indicates classes that implement interfaces, should not be forced to implement methods they do not use. This principle is related to the fact that a lot of specific interfaces are better than one general-purpose interface. In addition, this is the first principle, which is used in interface, all the previous principles applies on classes.</p>
<p>You might already noticed that we’ve already seen this violation in the chapter five:</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Managable</span></span>{
  <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">create</span><span class="hljs-params">()</span></span>
  <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">delete</span><span class="hljs-params">()</span></span>
}
</code></pre>
<p>First of all, people working with the above interface can not be sure what exactly are its boundaries at first glance. What exactly does "manage" mean in terms of our application? Is it just creating and deleting people, or should suspending also count in this case?</p>
<p>Furthermore, frequent violations of this rule may lead to the creation of a monolithic monster. And trust me, we don’t want to get back to such a code at some point in the future.</p>
<p>Similarly, we’ve already introduced a possible solution in the previous chapter:</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Creatable</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">create</span><span class="hljs-params">()</span></span>
}
<span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Deletable</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">delete</span><span class="hljs-params">()</span></span>
}
</code></pre>
<p>This time, we don’t have any doubts when working with the above interfaces. We can definitely assume that all classes implementing <em>Creatable</em> will be responsible for the creation, and in case of <em>Deletable-</em> for removal.</p>
<p><strong>Benefits</strong></p>
<ul>
<li><p>well designed interfaces help us to <strong>follow the other principles</strong>. It’s much easier to take care of single responsibility and as we could see- Liskov substitution</p>
</li>
<li><p>additionally, precise contract described by the interface makes the code <strong>less error-prone</strong></p>
</li>
<li><p>whatsoever, it really <strong>improves readability</strong> of the hierarchy and the codebase itself</p>
</li>
</ul>
<h1 id="heading-5-dependency-inversion-principle"><strong>5. D</strong>ependency inversion principle</h1>
<p>Finally, let’s check out the <strong>dependency inversion principle:</strong></p>
<blockquote>
<p><em>Depend upon abstractions, [not] concretions.</em></p>
</blockquote>
<p>This principle suggests that high level modules should not depend on low level. So, both should depend on abstractions. Furthermore, abstraction should not depend on details. Details should depend upon abstractions.</p>
<p>Just like in the previous examples, let’s see the code, which does not apply the above principle:</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">EmailNotificationService</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">sendEmail</span><span class="hljs-params">(message: <span class="hljs-type">String</span>)</span></span> {
    <span class="hljs-keyword">val</span> formattedMessage = message.uppercase()
    println(<span class="hljs-string">"Sending formatted message: <span class="hljs-variable">$formattedMessage</span>"</span>)
  }
}
</code></pre>
<p>As we can see, the <em>EmailNotificationService</em> will send a formatted to upper case message. Although everything is working as expected, we can spot that this method depends on the specific implementation.</p>
<p>Let’s modify the service a bit:</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">EmailNotificationService</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">sendEmail</span><span class="hljs-params">(message: <span class="hljs-type">String</span>, formatter: (<span class="hljs-type">String</span>) -&gt; <span class="hljs-type">String</span>)</span></span> {
    <span class="hljs-keyword">val</span> formattedMessage = formatter.invoke(message)
    println(<span class="hljs-string">"Sending formatted message: <span class="hljs-variable">$formattedMessage</span>"</span>)
  }
}
</code></pre>
<p>This time, we made the <em>EmailNotificationService</em> independent of the formatter implementation. The only thing that this service care about is that the formatter has to return a String value. As we can see, applying this principle gives us much more flexibility.</p>
<p><strong>Benefits</strong></p>
<ul>
<li><p>allows the codebase to be easily expanded and extended with new functionalities</p>
</li>
<li><p>furthermore, it improves reusability</p>
</li>
</ul>
<h1 id="heading-conclusion"><strong>Conclusion</strong></h1>
<p>Writing code according to SOLID principles will make our software more readable, understandable, flexible, and maintainable.</p>
<p><a class="user-mention" href="https://hashnode.com/@mansivaghela">Mansi Vaghela</a> <a target="_blank" href="https://www.linkedin.com/in/mansi-droid/"><strong>LinkedIn</strong></a> <a target="_blank" href="https://twitter.com/mansi_droid"><strong>Twitter</strong></a> <a target="_blank" href="https://github.com/mansi-droid"><strong>Github</strong></a> <a target="_blank" href="https://www.youtube.com/channel/UCoGcTjvUp32To72hQVe7iZw"><strong>Youtube</strong></a></p>
]]></content:encoded></item><item><title><![CDATA[Learn Object Oriented Concepts for Android Development in Kotlin]]></title><description><![CDATA[This article mainly focuses on how OOP theory can be applied on Android using Google’s latest language, Kotlin!
The 4 main concepts in OOP are Inheritance, Abstraction, Polymorphism and Encapsulation, The most fundamental reasoning behind using OOP c...]]></description><link>https://blog.mansi.dev/learn-object-oriented-concepts-for-android-development-in-kotlin</link><guid isPermaLink="true">https://blog.mansi.dev/learn-object-oriented-concepts-for-android-development-in-kotlin</guid><category><![CDATA[Programming Blogs]]></category><category><![CDATA[android app development]]></category><category><![CDATA[Android]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[Programming Tips]]></category><dc:creator><![CDATA[Mansi Vaghela]]></dc:creator><pubDate>Wed, 25 Jan 2023 09:52:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1674640047059/3054580c-1524-4d6a-b93c-41cc93e9b4d8.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This article mainly focuses on how OOP theory can be applied on Android using Google’s latest language, <a target="_blank" href="https://kotlinlang.org/docs/getting-started.html"><strong>Kotlin</strong></a>!</p>
<p>The 4 main concepts in OOP are <strong>Inheritance</strong>, <strong>Abstraction, Polymorphism</strong> and <strong>Encapsulation,</strong> The most fundamental reasoning behind using OOP concepts in projects is to allow developers to scale, test, and manage their projects efficiently.</p>
<h2 id="heading-inheritance"><strong>Inheritance</strong></h2>
<p>All classes in your project that have no defined superclass inherit from a common superclass called <a target="_blank" href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-any/"><strong>any</strong></a> in Kotlin. To make a class inheritable, you have to use the keyword <strong>open</strong> because by default a class is final and cannot be inheritable. In the simple example below, we have a class parent that has an inheritable function called <strong>eyeColor,</strong> and we have a child class that is able to access that function.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">open</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Favourite</span> </span>{
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">favColor</span><span class="hljs-params">(colorName:<span class="hljs-type">String</span>)</span></span> = 
println(<span class="hljs-string">"My child's eye color is <span class="hljs-variable">$colorName</span>"</span>)
}==========================================================
<span class="hljs-comment">//to inherit a class you type colon(:) and the name of parent class</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Color</span> : <span class="hljs-type">Favourite </span></span>(){
    <span class="hljs-keyword">init</span> {
        eyeColor(<span class="hljs-string">"Blue"</span>)
    }
}
</code></pre>
<h2 id="heading-abstraction"><strong>Abstraction</strong></h2>
<p>This class holds the definitions of functions needed by all the subclasses that are inheriting from it, abstract classes do not need to know the implementations, you can make a class abstract by using the keyword abstract, abstract classes cannot be instantiated (objects cannot be created).</p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">val</span> circle = Circle(<span class="hljs-number">5.0</span>)
    circle.shapeName(<span class="hljs-string">"Circle"</span>)    <span class="hljs-keyword">val</span> triangle = Triangle(<span class="hljs-number">2.0</span>,<span class="hljs-number">3.0</span>,<span class="hljs-number">4.0</span>)
    triangle.shapeName(<span class="hljs-string">"Triangle"</span>)
}
===================================================================
<span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Shape</span></span>{
    <span class="hljs-keyword">abstract</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">area</span><span class="hljs-params">()</span></span> : <span class="hljs-built_in">Double</span>
    <span class="hljs-keyword">abstract</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">perimeter</span><span class="hljs-params">()</span></span> : <span class="hljs-built_in">Double</span>
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">shapeName</span><span class="hljs-params">(name:<span class="hljs-type">String</span>)</span></span>{
        println(<span class="hljs-string">"The name of shape is <span class="hljs-variable">$name</span>"</span>)
    }
}
===================================================================
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Circle</span> </span>(<span class="hljs-keyword">var</span> radius : <span class="hljs-built_in">Double</span>): Shape(){
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> pi = <span class="hljs-number">3.14</span>
    <span class="hljs-keyword">init</span> {
        println(<span class="hljs-string">"The area of circle is <span class="hljs-subst">${area()}</span>"</span>)
        println(<span class="hljs-string">"The perimeter of circle is <span class="hljs-subst">${perimeter()}</span>"</span>)
    }
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">area</span><span class="hljs-params">()</span></span> = radius * radius * pi
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">perimeter</span><span class="hljs-params">()</span></span> = <span class="hljs-number">2</span> * radius * pi
}
===================================================================
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Triangle</span> </span>(<span class="hljs-keyword">var</span> a : <span class="hljs-built_in">Double</span>, <span class="hljs-keyword">var</span> b : <span class="hljs-built_in">Double</span>,<span class="hljs-keyword">var</span> c : <span class="hljs-built_in">Double</span>): Shape (){
    <span class="hljs-keyword">init</span> {
        println(<span class="hljs-string">"The area of Triangle is <span class="hljs-subst">${area()}</span>"</span>)
        println(<span class="hljs-string">"The perimeter of perimeter is <span class="hljs-subst">${perimeter()}</span>"</span>)
    }
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">area</span><span class="hljs-params">()</span></span>: <span class="hljs-built_in">Double</span> = sqrt((perimeter() / <span class="hljs-number">2</span>) * (perimeter() / <span class="hljs-number">2</span> - a) * (perimeter() / <span class="hljs-number">2</span> - b) * (perimeter() / <span class="hljs-number">2</span> - c))
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">perimeter</span><span class="hljs-params">()</span></span> = a + b + c
}
</code></pre>
<p>In the code above , circle and triangle class is instantiated in the main class and a name is passed as a parameter and inside the init block of these classes the methods is where the logic/implementation is handled. The shape class only has the definitions of the methods needed by any classes that inherits it.</p>
<h2 id="heading-encapsulations"><strong>Encapsulations</strong></h2>
<p>is a term used to describe the scope visibility of variables and functions in classes, there are 4 main types of <a target="_blank" href="https://kotlinlang.org/docs/visibility-modifiers.html">visibility modifiers</a></p>
<p><strong>Public</strong> , by default all classes and variables are public , which means they are accessible for the entire project.</p>
<p><strong>Private</strong>, variables and functions which are private can be accessed only within the class they are declared in.</p>
<p><strong>Protected</strong> , these variables and functions can be accessed within the class and all classes which inherit this class</p>
<p><a target="_blank" href="https://kotlinlang.org/docs/visibility-modifiers.html#modules"><strong>Internal</strong></a><strong>,</strong> internal allows visibility in the same module.</p>
<h2 id="heading-polymorphism"><strong>Polymorphism</strong></h2>
<p>Which means “occurring in several different forms”, can be demonstrated by overriding and overloading functions or variables.</p>
<p><strong>Overriding</strong> the process of re-declaring existing variables or functions in superclass for different implementations. to override a particular variable or function it must be declared using the open keyword in the superclass and then the keyword override should be used in the child class which overrides it.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">open</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Car</span> </span>{
<span class="hljs-keyword">open</span> <span class="hljs-keyword">val</span> speed:String = <span class="hljs-string">"Average speed 200Kmph"</span>}==========================================================<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bmw</span> : <span class="hljs-type">Car </span></span>(){
<span class="hljs-comment">//you can override a val with var but not vice versa</span>
<span class="hljs-keyword">override</span> <span class="hljs-keyword">val</span> speed = <span class="hljs-string">"Bmw speed 250Kmph"</span>
}
</code></pre>
<p><strong>overloading</strong> is done when you want create functions with similar functionality and name but also want the compiler to be able to distinguish each functions uniquely,you can overload a function by have different parameter types or different amount of parameters, overloading can also be seen through out your kotlin projects example such as the inbuilt println() function which can take any parameter.</p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
 println(<span class="hljs-string">"This is 1st methods max 1 : <span class="hljs-subst">${getMax(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>)}</span>"</span>)
 println(<span class="hljs-string">"This is 1st methods max 3 : <span class="hljs-subst">${getMax(<span class="hljs-number">6.4</span>, <span class="hljs-number">3</span>)}</span>"</span>)
 println(<span class="hljs-string">"This is 1st methods max 2 : <span class="hljs-subst">${getMax(<span class="hljs-number">2.4</span>, <span class="hljs-number">3.4</span>)}</span>"</span>)
 println(<span class="hljs-string">"This is 1st methods max 4: <span class="hljs-subst">${getMax(<span class="hljs-number">4</span>, <span class="hljs-number">3</span> , <span class="hljs-string">"4th get max"</span>)}</span>"</span>)
}
<span class="hljs-comment">//1</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getMax</span><span class="hljs-params">(a: <span class="hljs-type">Int</span>, b: <span class="hljs-type">Int</span>)</span></span> = <span class="hljs-keyword">if</span> (a &gt; b) a <span class="hljs-keyword">else</span> b
<span class="hljs-comment">//2</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getMax</span><span class="hljs-params">(a: <span class="hljs-type">Double</span>, b: <span class="hljs-type">Double</span>)</span></span> = <span class="hljs-keyword">if</span> (a &gt; b) a <span class="hljs-keyword">else</span> b
<span class="hljs-comment">//3</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getMax</span><span class="hljs-params">(a: <span class="hljs-type">Double</span>, b: <span class="hljs-type">Int</span>)</span></span> = <span class="hljs-keyword">if</span> (a &gt; b) a <span class="hljs-keyword">else</span> b
<span class="hljs-comment">//4</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getMax</span><span class="hljs-params">(a: <span class="hljs-type">Int</span>, b: <span class="hljs-type">Int</span>, c:<span class="hljs-type">String</span>)</span></span> = <span class="hljs-keyword">if</span> (a &gt; b) a <span class="hljs-keyword">else</span> c
</code></pre>
<p>This article was an overview of these basic concepts in kotlin , you can check out the kotlin documentation for more information :</p>
<p><a target="_blank" href="https://kotlinlang.org/docs/home.html">https://kotlinlang.org/docs/home.html</a></p>
<p><a class="user-mention" href="https://hashnode.com/@mansivaghela">Mansi Vaghela</a> <a target="_blank" href="https://www.linkedin.com/in/mansi-droid/"><strong>LinkedIn</strong></a> <a target="_blank" href="https://twitter.com/mansi_droid"><strong>Twitter</strong></a> <a target="_blank" href="https://github.com/mansi-droid"><strong>Github</strong></a> <a target="_blank" href="https://www.youtube.com/channel/UCoGcTjvUp32To72hQVe7iZw"><strong>Youtube</strong></a></p>
]]></content:encoded></item></channel></rss>