<?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[Hardik Sachan]]></title><description><![CDATA[Hardik Sachan]]></description><link>https://hardiksachan.com</link><generator>RSS for Node</generator><lastBuildDate>Sun, 12 Apr 2026 12:49:17 GMT</lastBuildDate><atom:link href="https://hardiksachan.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Graceful Retries In Go]]></title><description><![CDATA[Failures are Inevitable
Network calls might time out, APIs might be temporarily unavailable, or databases might become unreachable. To handle such transient errors gracefully, implementing a retry mechanism is crucial. This article will guide you thr...]]></description><link>https://hardiksachan.com/graceful-retries-in-go</link><guid isPermaLink="true">https://hardiksachan.com/graceful-retries-in-go</guid><category><![CDATA[Go Language]]></category><category><![CDATA[retry strategy]]></category><dc:creator><![CDATA[Hardik Sachan]]></dc:creator><pubDate>Sat, 08 Jun 2024 18:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/XN4T2PVUUgk/upload/6fadc89441b85530ad6dcebb13ee249d.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Failures are Inevitable</p>
<p>Network calls might time out, APIs might be temporarily unavailable, or databases might become unreachable. To handle such transient errors gracefully, implementing a retry mechanism is crucial. This article will guide you through the basics of why you need a retry mechanism, starting with simple retries and gradually introducing backoff strategies using a Go example.</p>
<h3 id="heading-simple-retries">Simple Retries</h3>
<p>A basic retry mechanism involves reattempting an operation a fixed number of times immediately after a failure. Here's how you can implement this in Go:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">immediatelyRetry</span><span class="hljs-params">(f <span class="hljs-keyword">func</span>()</span> <span class="hljs-title">error</span>, <span class="hljs-title">retriesLeft</span> <span class="hljs-title">int</span>) <span class="hljs-title">error</span></span> {
    err := f()
    <span class="hljs-keyword">if</span> err == <span class="hljs-literal">nil</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span>
    }

    <span class="hljs-keyword">if</span> retriesLeft == <span class="hljs-number">0</span> {
        <span class="hljs-keyword">return</span> err
    }

    <span class="hljs-keyword">return</span> immediatelyRetry(f, retriesLeft<span class="hljs-number">-1</span>)
}
</code></pre>
<p>In this function, <code>f</code> is the operation that might fail. It is retried immediately until it either succeeds or the retry limit is reached.</p>
<h3 id="heading-adding-backoff-strategies">Adding Backoff Strategies</h3>
<p>While immediate retries can be effective, they might overwhelm the system or the external service you're interacting with. To address this, backoff strategies introduce delays between retries, with the delay increasing over time.</p>
<h4 id="heading-exponential-backoff">Exponential Backoff</h4>
<p>Exponential backoff is a popular strategy where the delay between retries grows exponentially. This reduces the load on the system and gives it more time to recover. Here's an example implementation:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">retryWithBackoff</span><span class="hljs-params">(f <span class="hljs-keyword">func</span>()</span> <span class="hljs-title">error</span>, <span class="hljs-title">retriesLeft</span> <span class="hljs-title">int</span>, <span class="hljs-title">delay</span> <span class="hljs-title">time</span>.<span class="hljs-title">Duration</span>, <span class="hljs-title">backoff</span> <span class="hljs-title">float64</span>) <span class="hljs-title">error</span></span> {
    err := f()
    <span class="hljs-keyword">if</span> err == <span class="hljs-literal">nil</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span>
    }

    <span class="hljs-keyword">if</span> retriesLeft == <span class="hljs-number">0</span> {
        <span class="hljs-keyword">return</span> err
    }

    time.Sleep(delay)
    <span class="hljs-keyword">return</span> retryWithBackoff(f, retriesLeft<span class="hljs-number">-1</span>, time.Duration(<span class="hljs-keyword">float64</span>(delay)*backoff), backoff)
}
</code></pre>
<p>In this function, the delay is multiplied by the backoff factor after each retry, resulting in exponentially increasing delays.</p>
<h3 id="heading-defining-a-custom-retry-policy">Defining a Custom Retry Policy</h3>
<p>To provide flexibility, you can define a custom retry policy that combines immediate retries and retries with backoff. Here’s how you can achieve this in Go:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> xretry

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"time"</span>
)

<span class="hljs-comment">// RetryPolicy is the retry policy</span>
<span class="hljs-keyword">type</span> RetryPolicy <span class="hljs-keyword">struct</span> {
    immediateRetries   <span class="hljs-keyword">int</span>
    retriesWithBackoff <span class="hljs-keyword">int</span>
    delay              time.Duration
    backoffFactor      <span class="hljs-keyword">float64</span>
}

<span class="hljs-comment">// RetryPolicyOption is the option for the retry policy</span>
<span class="hljs-keyword">type</span> RetryPolicyOption <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(*RetryPolicy)</span></span>

<span class="hljs-comment">// WithImmediateRetries sets the immediate retries</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">WithImmediateRetries</span><span class="hljs-params">(retries <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">RetryPolicyOption</span></span> {
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(p *RetryPolicy)</span></span> {
        p.immediateRetries = retries
    }
}

<span class="hljs-comment">// WithRetriesWithBackoff sets the retries with backoff</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">WithRetriesWithBackoff</span><span class="hljs-params">(retries <span class="hljs-keyword">int</span>, delay time.Duration, backoffFactor <span class="hljs-keyword">float64</span>)</span> <span class="hljs-title">RetryPolicyOption</span></span> {
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(p *RetryPolicy)</span></span> {
        p.retriesWithBackoff = retries
        p.delay = delay
        p.backoffFactor = backoffFactor
    }
}

<span class="hljs-comment">// NewRetryPolicy creates a new RetryPolicy</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">NewRetryPolicy</span><span class="hljs-params">(opts ...RetryPolicyOption)</span> <span class="hljs-title">RetryPolicy</span></span> {
    p := RetryPolicy{
        immediateRetries:   <span class="hljs-number">0</span>,
        retriesWithBackoff: <span class="hljs-number">0</span>,
        delay:              <span class="hljs-number">0</span>,
        backoffFactor:      <span class="hljs-number">0</span>,
    }

    <span class="hljs-keyword">for</span> _, opt := <span class="hljs-keyword">range</span> opts {
        opt(&amp;p)
    }

    <span class="hljs-keyword">return</span> p
}

<span class="hljs-comment">// Retrier is the interface that wraps the Retry method</span>
<span class="hljs-keyword">type</span> Retrier <span class="hljs-keyword">struct</span> {
    p RetryPolicy
}

<span class="hljs-comment">// NewRetrier creates a new Retrier</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">NewRetrier</span><span class="hljs-params">(p RetryPolicy)</span> *<span class="hljs-title">Retrier</span></span> {
    <span class="hljs-keyword">return</span> &amp;Retrier{
        p: p,
    }
}

<span class="hljs-comment">// Retry will retry the given function</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(r *Retrier)</span> <span class="hljs-title">Retry</span><span class="hljs-params">(f <span class="hljs-keyword">func</span>()</span> <span class="hljs-title">error</span>) <span class="hljs-title">error</span></span> {
    err := immediatelyRetry(f, r.p.immediateRetries)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        err = retryWithBackoff(f, r.p.retriesWithBackoff, r.p.delay, r.p.backoffFactor)
        <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
            <span class="hljs-keyword">return</span> err
        }
    }

    <span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span>
}
</code></pre>
<h3 id="heading-usage-example">Usage Example</h3>
<p>Here's an example of how to use the custom retry policy and retrier in your application:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    <span class="hljs-comment">// Define a retry policy</span>
    policy := xretry.NewRetryPolicy(
        xretry.WithImmediateRetries(<span class="hljs-number">3</span>),
        xretry.WithRetriesWithBackoff(<span class="hljs-number">3</span>, <span class="hljs-number">1</span>*time.Second, <span class="hljs-number">2.0</span>),
    )

    <span class="hljs-comment">// Create a new retrier with the policy</span>
    retrier := xretry.NewRetrier(policy)

    <span class="hljs-comment">// Define a function that may fail</span>
    f := <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span> <span class="hljs-title">error</span></span> {
        <span class="hljs-comment">// Your code here</span>
    }

    <span class="hljs-comment">// Use the retrier to retry the function if it fails</span>
    err := retrier.Retry(f)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        fmt.Println(<span class="hljs-string">"Operation failed after retries:"</span>, err)
    }
}
</code></pre>
<p>In this example, the function <code>f</code> will be retried immediately 3 times if it fails. If it still fails after these retries, it will be retried 3 more times with a delay that doubles after each retry, starting from 1 second.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Implementing a retry mechanism with customizable policies and backoff strategies can significantly enhance the resilience of your Go applications. By defining flexible retry policies, you can handle transient errors more gracefully, providing a better experience for your users and reducing the need for manual intervention.</p>
]]></content:encoded></item><item><title><![CDATA[Guide to Sealed Classes in Kotlin for Improved Code Organization]]></title><description><![CDATA[In the last article, we covered data classes in Kotlin. We saw how they simplify class creation and make it faster with less coding. Now, let's explore Sealed Classes.
Sealed Classes in Kotlin are a specialized form of abstract classes. They limit su...]]></description><link>https://hardiksachan.com/guide-to-sealed-classes-in-kotlin-for-improved-code-organization</link><guid isPermaLink="true">https://hardiksachan.com/guide-to-sealed-classes-in-kotlin-for-improved-code-organization</guid><category><![CDATA[Android]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[sealed class]]></category><category><![CDATA[learning]]></category><dc:creator><![CDATA[Hardik Sachan]]></dc:creator><pubDate>Tue, 07 Feb 2023 11:51:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1676202694765/b218c054-a1ce-42c8-9be7-ed49de4c22c5.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the <a target="_blank" href="https://hardiksachan.hashnode.dev/kotlin-data-classes-101-understanding-syntax-usage-and-inheritance">last article</a>, we covered data classes in Kotlin. We saw how they simplify class creation and make it faster with less coding. Now, let's explore Sealed Classes.</p>
<p><strong>Sealed Classes</strong> in Kotlin are a specialized form of abstract classes. They limit subclassing, giving you more control. This article will explain what sealed classes are, how they benefit you in Kotlin, and the best ways to use them.</p>
<p>Sealed Classes in Kotlin are a type of abstract class that can't be initiated directly, with abstract members. They limit subclassing, ensuring a class only has a limited, well-defined set of subclasses. This improves type-safety and helps write error-free code.</p>
<p>In this article, we'll cover the basics of Sealed Classes: syntax, constructors, and subclass restrictions. We'll also see how Sealed Classes can be used in <code>when</code> expressions for a more controlled, type-safe handling of cases. Whether you're new to Kotlin or a seasoned developer, you'll gain valuable insights on using Sealed Classes effectively.</p>
<h2 id="heading-poperties-and-overview">Poperties and Overview</h2>
<p>Sealed Classes in Kotlin limit the type hierarchy. They're like restricted abstract classes, having constructors and the ability to extend classes. But, unlike <code>open</code> or <code>abstract</code> classes, they cannot be inherited outside their file or package.</p>
<p>An example of a Sealed Class in Kotlin:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">sealed</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Error</span> </span>{
    <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">val</span> message: String
}
</code></pre>
<p>The visibility of Sealed Class constructors is based on the visibility of the class. If the Sealed Class is private, its constructors will also be private. If it's internal, the constructors will be internal and so on.</p>
<p>Sealed classes in Kotlin have a limitation on inheritance. The direct descendants of a sealed class must be located in the same file or package as the sealed class itself. It's not possible to create a subclass of a sealed class in a different file or package.</p>
<p>Here's an illustration of two subclasses of the Error sealed class in the same file:</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">FileReadError</span></span>(<span class="hljs-keyword">override</span> <span class="hljs-keyword">val</span> message: String, <span class="hljs-keyword">val</span> file: String) : Error()

<span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DatabaseError</span></span>(<span class="hljs-keyword">override</span> <span class="hljs-keyword">val</span> message: String, <span class="hljs-keyword">val</span> source: String) : Error()
</code></pre>
<p>Additionally, the subclasses of a sealed class must have a fully qualified name and cannot be defined as <em>local</em> or <em>anonymous</em> objects.</p>
<h2 id="heading-control-flow">Control Flow</h2>
<p>The usage of sealed classes in Kotlin offers improved control over control flow statements. One of the key advantages of sealed classes is demonstrated through their utilization in <code>when</code> expressions.</p>
<p><code>when</code> expressions in Kotlin are comparable to switch statements in other programming languages. They let you inspect the class type of an object and perform different operations based on its type. <em>Unlike</em> switch statements, it is mandatory to include an <code>else</code> clause to cater to cases not covered in traditional switch statements.</p>
<p>With sealed classes, it is possible to verify that the <code>when</code> statement covers all cases, eliminating the need for an <code>else</code> clause. Consider the following example:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">sealed</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Error</span></span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FileReadError</span> : <span class="hljs-type">Error</span></span>()
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DatabaseError</span> : <span class="hljs-type">Error</span></span>()
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RuntimeError</span> : <span class="hljs-type">Error</span></span>()

<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">log</span><span class="hljs-params">(e: <span class="hljs-type">Error</span>)</span></span> = <span class="hljs-keyword">when</span>(e) {
    <span class="hljs-keyword">is</span> FileReadError -&gt; { println(<span class="hljs-string">"Error while reading file"</span>) }
    <span class="hljs-keyword">is</span> DatabaseError -&gt; { println(<span class="hljs-string">"Error reading from database"</span>) }
    <span class="hljs-keyword">is</span> RuntimeError -&gt;  { println(<span class="hljs-string">"Runtime error"</span>) }
    <span class="hljs-comment">// the `else` clause is not required because all the cases are covered</span>
}
</code></pre>
<p>In the example, <code>Error</code> is defined as a sealed class, with subclasses <code>FileReadError</code>, <code>DatabaseError</code>, and <code>RuntimeError</code>. The <code>when</code> expression within the <code>log</code> function checks the type of error and prints a corresponding message for each case.</p>
<p>Sealed classes in a when expression offer clear and reliable code, as all cases are accounted for, and there's no need for an else clause.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Sealed classes in Kotlin are a valuable tool for better type safety and control flow in your code. When used with <code>when</code> expressions, they restrict the objects that can be passed and make it simpler to guarantee all cases are handled. Additionally, sealed classes enforce proper naming conventions and keep subclasses in the same package, helping maintain code integrity and readability. Whether you are a beginner or an experienced developer, sealed classes are a must-have for writing superior code in Kotlin.</p>
<p>Happy Coding.</p>
]]></content:encoded></item><item><title><![CDATA[Kotlin Data Classes 101: Understanding Syntax, Usage and Inheritance]]></title><description><![CDATA[Welcome back to this series of articles on Android Development with Kotlin and Jetpack Compose. In the previous article, we discussed the type system in Kotlin along with null safety. In this article, we will take a look at what data classes are, how...]]></description><link>https://hardiksachan.com/kotlin-data-classes-101-understanding-syntax-usage-and-inheritance</link><guid isPermaLink="true">https://hardiksachan.com/kotlin-data-classes-101-understanding-syntax-usage-and-inheritance</guid><category><![CDATA[Kotlin]]></category><category><![CDATA[Android]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[learning]]></category><category><![CDATA[Jetpack Compose]]></category><dc:creator><![CDATA[Hardik Sachan]]></dc:creator><pubDate>Sat, 28 Jan 2023 10:17:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1674901426825/3bb7e18f-baf8-470d-99a4-5ec6fcc9676c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Welcome back to <a target="_blank" href="https://hardiksachan.hashnode.dev/series/android-zero-to-hero">this series</a> of articles on Android Development with Kotlin and Jetpack Compose. In the <a target="_blank" href="https://hardiksachan.hashnode.dev/exploring-the-kotlin-type-system-and-understanding-null-safety">previous article</a>, we discussed the type system in Kotlin along with null safety. In this article, we will take a look at what data classes are, how they differ from regular classes, and how to use them effectively in your Android app development.</p>
<p>Kotlin provides us with a special modifier for classes - <code>data</code>. Such classes are known as data classes. They are typically used to represent a data model in an application, such as a user or a product. These data classes provide useful functionalities out f the box, such as <code>equals()</code>, <code>hashCode()</code>, and <code>toString()</code> methods, which are automatically generated for us by the compiler. This can save us a lot of time and make our code more readable and maintainable.</p>
<p>Let's get started!</p>
<h2 id="heading-syntax-and-usage">Syntax And Usage</h2>
<p>Let's see how can we model a <code>User</code> class using data classes. We'll store two properties <code>name</code> and <code>age</code>.</p>
<p>To declare a data class use the <code>data</code> keyword, followed by the class declaration. Make sure that there is at least one property in the primary constructor.</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">User</span></span>(<span class="hljs-keyword">val</span> name: String, <span class="hljs-keyword">val</span> age: <span class="hljs-built_in">Int</span>)
</code></pre>
<p>The <code>val</code> keyword in front of the properties indicates that they are read-only, and can only be initialized in the primary constructor. We can also use <code>var</code> to make the properties mutable.</p>
<p>We can create an instance of a data class similar to that of regular classes. For example:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> user = User(<span class="hljs-string">"John"</span>, <span class="hljs-number">30</span>)
</code></pre>
<p>We can then access the properties of the <code>User</code> class using the dot notation:</p>
<pre><code class="lang-kotlin">println(user.name) <span class="hljs-comment">// prints "John"</span>
println(user.age) <span class="hljs-comment">// prints 30</span>
</code></pre>
<p>One of the main benefits of data classes is that they come with several automatically generated functions that make it easy to work with instances of the class. These functions include:</p>
<ul>
<li><p><code>equals()</code>: This function compares two instances of the data class for equality. It is generated based on the properties defined in the primary constructor.</p>
</li>
<li><p><code>hashCode()</code>: This function generates a unique hash code for an instance of the data class. It is also generated based on the properties defined in the primary constructor.</p>
</li>
<li><p><code>toString()</code>: This function generates a string representation of an instance of the data class. The default implementation includes the class name and the values of the properties.</p>
</li>
</ul>
<p>Let's see how we can use the <code>equals()</code> function to compare two instances of the <code>User</code> class:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> user1 = User(<span class="hljs-string">"John"</span>, <span class="hljs-number">30</span>)
<span class="hljs-keyword">val</span> user2 = User(<span class="hljs-string">"John"</span>, <span class="hljs-number">30</span>)
<span class="hljs-keyword">val</span> user3 = User(<span class="hljs-string">"Jane"</span>, <span class="hljs-number">25</span>)

println(user1 == user2) <span class="hljs-comment">// prints true</span>
println(user1 == user3) <span class="hljs-comment">// prints false</span>
</code></pre>
<p>We can also use the <code>toString()</code> function to get a string representation of an instance of the data class:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> user = User(<span class="hljs-string">"John"</span>, <span class="hljs-number">30</span>)
println(user) <span class="hljs-comment">// prints "User(name=John, age=30)"</span>
</code></pre>
<p>In this section, we covered the syntax and usage of data classes in Kotlin, including how to define a data class, create an instance of a data class, access its properties, and use the automatically generated functions such as <code>equals()</code>, <code>hashCode()</code>, and <code>toString()</code>.</p>
<h2 id="heading-properties-declared-in-the-class-body">Properties Declared in the class body</h2>
<p>In the previous section, we took a look at how to create a data class. We declared the properties in the primary constructor but we can also declare some properties in the class body. These properties are not considered part of the primary constructor and are not included in the automatically generated functions such as <code>equals()</code>, <code>hashCode()</code>, and <code>toString()</code>. However, they can still be accessed and used like any other property.</p>
<p>For example, consider the following data class:</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">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-number">0</span>
}
</code></pre>
<p>In this example, <code>name</code> is a property of the primary constructor and <code>age</code> is a property declared in the class body. When comparing two <code>Person</code> objects using the <code>==</code> operator, only the <code>name</code> property will be considered.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> person1 = Person(<span class="hljs-string">"John"</span>)
<span class="hljs-keyword">val</span> person2 = Person(<span class="hljs-string">"John"</span>)
person1.age = <span class="hljs-number">10</span>
person2.age = <span class="hljs-number">20</span>

println(<span class="hljs-string">"person1 == person2: <span class="hljs-subst">${person1 == person2}</span>"</span>)
</code></pre>
<p>This will result in <code>person1 == person2: true</code>, even though the <code>age</code> property is different between the two objects.</p>
<p>In addition, the <code>toString()</code>, <code>hashCode()</code>, and <code>copy()</code> functions will also only include the <code>name</code> property. If we wish to include additional properties in these functions, we can override them in the class body.</p>
<p>It's important to keep in mind that properties declared in the class body are not considered part of the data class' signature, and thus will not affect the automatically generated functions. They can be used for additional functionality and can be used to store additional data, but it's important to consider the trade-offs.</p>
<h2 id="heading-copy"><code>Copy()</code></h2>
<p>In Kotlin, the <code>copy()</code> function is a convenient way to create a new instance of a data class while altering some or all of its properties. The <code>copy()</code> function is generated automatically by the compiler for data classes and takes all properties of the class as its parameters. The values passed to the <code>copy()</code> function will be used to create a new instance of the class, while the values that are not passed will be taken from the original instance.</p>
<p>Here is an example of using the <code>copy()</code> function in a data class:</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">Person</span></span>(<span class="hljs-keyword">val</span> name: String, <span class="hljs-keyword">val</span> age: <span class="hljs-built_in">Int</span>)

<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> person1 = Person(<span class="hljs-string">"John"</span>, <span class="hljs-number">25</span>)
    <span class="hljs-keyword">val</span> person2 = person1.copy(age = <span class="hljs-number">30</span>)
    println(person1) <span class="hljs-comment">// Person(name=John, age=25)</span>
    println(person2) <span class="hljs-comment">// Person(name=John, age=30)</span>
}
</code></pre>
<p>In this instance, <code>person1</code> is an instance of the <code>Person</code> data class, with the name "John" and age 25. Using the <code>copy()</code> function, we modify the age to 30 and create a new instance of the class, <code>person2</code>. As we can see, two unique instances with different age values arise from copying the name property from the original instance and setting the age property to the new value.</p>
<p>It's important to keep in mind that the <code>copy()</code> function creates a new object with the provided properties rather than <em>altering</em> the original object. This makes it a helpful tool for making minor changes to existing instances before creating new ones.</p>
<p>In conclusion, the <code>copy()</code> function in Kotlin is a simple yet powerful tool for creating new instances of data classes with modified properties. It's easy to use, and it helps to keep your code clean and readable.</p>
<h2 id="heading-desctructuting-decarations-with-data-classes">Desctructuting decarations with data classes</h2>
<p>Data classes in Kotlin come with a set of automatically generated functions, including component functions. These component functions make it possible to use data classes in destructuring declarations.</p>
<p>A destructuring declaration is a way to decompose an object into its individual properties. It allows you to assign the properties of an object to separate variables in a single line. For example, consider the following data class:</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">Person</span></span>(<span class="hljs-keyword">val</span> name: String, <span class="hljs-keyword">val</span> age: <span class="hljs-built_in">Int</span>)
</code></pre>
<p>We can create an instance of this class and use it in a destructuring declaration as follows:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> jane = Person(<span class="hljs-string">"Jane"</span>, <span class="hljs-number">35</span>)
<span class="hljs-keyword">val</span> (name, age) = jane
println(<span class="hljs-string">"<span class="hljs-variable">$name</span>, <span class="hljs-variable">$age</span> years of age"</span>) <span class="hljs-comment">// prints "Jane, 35 years of age"</span>
</code></pre>
<p>In this example, the variables <code>name</code> and <code>age</code> are assigned the values of the <code>name</code> and <code>age</code> properties of the <code>jane</code> object, respectively. The variables are created and initialized in a single line, making the code more concise and readable.</p>
<p>It is also possible to use destructuring declarations with a specific component function. For example, if we only need the name property of the object, we can use the <code>component1()</code> function which is generated for the first property of the data class.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> (name) = jane
println(<span class="hljs-string">"Name: <span class="hljs-variable">$name</span>"</span>) <span class="hljs-comment">// prints "Name: Jane"</span>
</code></pre>
<p>In summary, destructuring declarations provides a convenient and readable way to work with the properties of data classes. They allow us to easily access and assign the properties of an object without having to reference the object itself. This can make our code more readable and maintainable.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In conclusion, data classes in Kotlin provide a simple and efficient way to define classes that hold data. They allow developers to quickly create classes with minimal boilerplate code and automatically generated functions such as <code>equals()</code>, <code>hashCode()</code>, and <code>toString()</code>. They also provide a convenient way to copy objects and use them in destructuring declarations.</p>
<p>In the coming article, we'll discuss sealed classes. See you then.</p>
<p>Happy Hacking!</p>
]]></content:encoded></item><item><title><![CDATA[Exploring the Kotlin Type System and understanding Null Safety]]></title><description><![CDATA[Welcome to the fourth article in this series on Android Development. In the previous articles, we covered some basics of Kotlin and OOPS. In this article, we're going to dive deep into Kotlin's type system and learn all about null safety.
First, let'...]]></description><link>https://hardiksachan.com/exploring-the-kotlin-type-system-and-understanding-null-safety</link><guid isPermaLink="true">https://hardiksachan.com/exploring-the-kotlin-type-system-and-understanding-null-safety</guid><category><![CDATA[Android]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[android app development]]></category><category><![CDATA[learning]]></category><dc:creator><![CDATA[Hardik Sachan]]></dc:creator><pubDate>Sat, 14 Jan 2023 17:43:11 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1673718131997/9cdafe19-e59f-4e5b-82a2-5fb569a0e86a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Welcome to the fourth article in <a target="_blank" href="https://hardiksachan.hashnode.dev/series/android-zero-to-hero">this series</a> on Android Development. In the <a target="_blank" href="https://hardiksachan.hashnode.dev/kotlin-polymorphism-and-inheritance-essential-concepts-for-android-developers">previous articles</a>, we covered some basics of Kotlin and OOPS. In this article, we're going to dive deep into Kotlin's type system and learn all about null safety.</p>
<p>First, let's define what a type system is. In programming, a type system is a set of rules that determine how data is stored, modified, and used. Coming to the second part of our article, we'll discuss why we need to be concerned with null safety. Accessing a type that can be null can result in a null reference exception, commonly known as a <code>NullPointerException</code>. According to a <a target="_blank" href="https://www.overops.com/blog/the-top-10-exceptions-types-in-production-java-applications-based-on-1b-events/">survey</a>, <code>NullPointerException</code> is the most common exception in java applications. But don't worry, Kotlin offers a solution for this.</p>
<p>The type system of Kotlin is designed to provide an effective way to manage null references. It makes a clear distinction between references that can hold null values (nullable references) and those that cannot (non-null references). Hence, the compiler can track values which can be null and warn you if you're trying to access nullable value, preventing an <code>NullPointerException</code> from happening.</p>
<p>With the introduction out of the way, let's get started!</p>
<h2 id="heading-basic-types">Basic Types</h2>
<p>The data type is one of the most fundamental concepts in any programming language. Simply put, a type is a category of data that a variable or expression can hold. In Kotlin, several basic types are available to use when declaring variables and constants. These basic types include numbers, characters, and booleans. These different types are very neatly organized in a hierarchy that we'll take a look at after we understand nullable types.</p>
<h3 id="heading-numbers">Numbers</h3>
<p>Numbers in Kotlin come in two forms: Integers and Floating-point numbers. Integers are represented by types such as <code>Byte</code>, <code>Short</code>, <code>Int</code>, and <code>Long</code>. For example,</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> age: <span class="hljs-built_in">Int</span> = <span class="hljs-number">25</span>
<span class="hljs-keyword">val</span> weight: <span class="hljs-built_in">Long</span> = <span class="hljs-number">150</span>
</code></pre>
<p>Floating-point numbers include types such as Float and Double. For example,</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> price: <span class="hljs-built_in">Double</span> = <span class="hljs-number">12.99</span>
<span class="hljs-keyword">val</span> temperature: <span class="hljs-built_in">Float</span> = <span class="hljs-number">32.5f</span>
</code></pre>
<p>Also, you can use <code>_</code> to make increase the readability of code.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> largeNum: <span class="hljs-built_in">Long</span> = <span class="hljs-number">1_000_000_000</span>
</code></pre>
<h3 id="heading-characters">Characters</h3>
<p>Characters in Kotlin are represented by the <code>Char</code> type. They are enclosed in single quotes, for example:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> letter: <span class="hljs-built_in">Char</span> = <span class="hljs-string">'A'</span>
</code></pre>
<h3 id="heading-booleans">Booleans</h3>
<p>Booleans in Kotlin is represented by the <code>Boolean</code> type. They can be either <code>true</code> or <code>false</code>. For example,</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> isStudent: <span class="hljs-built_in">Boolean</span> = <span class="hljs-literal">true</span>
<span class="hljs-keyword">val</span> isTired: <span class="hljs-built_in">Boolean</span> = <span class="hljs-literal">false</span>
</code></pre>
<p>In addition to these basic types, Kotlin also supports strings, arrays and enum types.</p>
<h3 id="heading-strings">Strings</h3>
<p>Kotlin's string type is similar to the string type in most programming languages. It is used to represent a sequence of characters. For example,</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> name: String = <span class="hljs-string">"John Doe"</span>
</code></pre>
<h3 id="heading-arrays">Arrays</h3>
<p>Arrays in Kotlin are similar to arrays in most programming languages. They are used to store a fixed-size sequential collection of elements of the same type. For example,</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> numbers: IntArray = intArrayOf(<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-number">5</span>)
<span class="hljs-keyword">val</span> names: Array&lt;String&gt; = arrayOf(<span class="hljs-string">"John"</span>, <span class="hljs-string">"Doe"</span>, <span class="hljs-string">"Jane"</span>, <span class="hljs-string">"Smith"</span>)
</code></pre>
<p>Let's also discuss three special types in Kotlin, <code>Any</code>, <code>Unit</code> and <code>Nothing</code>.</p>
<h3 id="heading-any">Any</h3>
<p>As I mentioned above, all types in Kotlin are organized into a hierarchy, <code>Any</code> is at the root of that hierarchy. For instance, <code>Int</code> and <code>Boolean</code> are subtype of <code>Any</code>. Also, all the classes that you create are subtypes of <code>Any</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1673715969179/06472cf2-26c9-45db-a3f5-aaa15054fc1b.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-unit">Unit</h3>
<p><code>Unit</code> is a pre-defined type in Kotlin. It is a singleton, meaning there is only one instance of it. The unit type is used to represent the absence of a value. For example, if you have a function that does not need to return a value, you'd use <code>Unit</code> as its return type.</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">()</span></span>: <span class="hljs-built_in">Unit</span> {
    println(<span class="hljs-string">"Hello, World!"</span>)
}
</code></pre>
<p>Also, if you don't specifically mention a return type for the function, it's assumed to return Unit. Hence, the above code can be rewritten as:</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">()</span></span> {
   println(<span class="hljs-string">"Hello, World!"</span>)
}
</code></pre>
<h3 id="heading-nothing">Nothing</h3>
<p><code>Nothing</code> is a special type in Kotlin. It is at the very bottom of the type hierarchy. This means that Nothing is a subtype of every type. Also, the type <code>Nothing</code> can not be initialized and hence, can not have any instance. Please note the difference between <code>Unit</code> and <code>Nothing</code>. Evaluation of an expression type Unit results in the singleton value <code>Unit</code>. Evaluation of an expression of type Nothing never returns at all.</p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">throwsException</span><span class="hljs-params">()</span></span>: <span class="hljs-built_in">Nothing</span> {
    <span class="hljs-keyword">throw</span> Exception()
}
</code></pre>
<p>Please note that Kotlin is a type-safe language, which means that the compiler checks the types of variables and constants at <em>compile time</em> to ensure that they match the expected types.</p>
<h2 id="heading-null-safety">Null Safety</h2>
<p>As we previously discussed, accessing a type that can be null can result in a null reference exception, commonly known as a <code>NullPointerException</code>. Let's see how we can deal with null references in Kotlin.</p>
<p>Kotlin's type system is designed in such a way that it distinguishes between variables that can hold a <code>null</code> value(nullable references) and those that cannot(non-nullable references).</p>
<p>For example, a regular variable of type <code>String</code> cannot hold <code>null</code>:</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">// Regular initialization means non-null by default</span>
<span class="hljs-keyword">var</span> a: String = <span class="hljs-string">"abc"</span> 

a = <span class="hljs-literal">null</span> <span class="hljs-comment">// compilation error</span>
</code></pre>
<p>To declare a variable that can be set to <code>null</code>, append <code>?</code> at the end of the type. For example, a nullable String should be declared as <code>String?</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">var</span> b: String? = <span class="hljs-string">"abc"</span> <span class="hljs-comment">// can be set to null</span>
b = <span class="hljs-literal">null</span>               <span class="hljs-comment">// ok</span>
</code></pre>
<p>In this way, if you call a method or access a property on <code>a</code>, it's guaranteed not to cause throw a <code>NullPointerException</code>, so it is safe to say:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> l = a.length
</code></pre>
<p>However, if you want to access the same property on <code>b</code>, that would not be safe and the compiler will report an error:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> l = b.length <span class="hljs-comment">// error: variable 'b' can be null</span>
</code></pre>
<p>But don't worry, there are ways to safely access properties on nullable variables, which we will discuss later in the article. But first, let's take a look at the type hierarchy in Kotlin.</p>
<h2 id="heading-type-hierarchy-in-kotlin">Type Hierarchy in Kotlin</h2>
<p>As we discussed above, <code>Any</code> type is the supertype for all the types, hence it is placed at the "top" of the hierarchy</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1673716064486/1ea5944b-be9e-4296-8a25-86784a488d51.png" alt class="image--center mx-auto" /></p>
<p>All the custom types (classes, interfaces, etc) that don't have an explicit type are also a sub-type of <code>Any</code> type. For instance,</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Box</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">render</span><span class="hljs-params">()</span></span> {
        <span class="hljs-comment">// function body</span>
    }
}
</code></pre>
<p>The type <code>Box</code> is a subtype of <code>Any</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1673716334502/fda42cfa-3fe3-46db-a95d-bab08259b018.png" alt class="image--center mx-auto" /></p>
<p>Now, the types that inherit other types form a tree structure in the hierarchy. A type can have multiple parent types. For instance,</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">IClickable</span></span>
<span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">IDragable</span></span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Card</span>: <span class="hljs-type">Box</span>, <span class="hljs-type">IClickable</span>, <span class="hljs-type">IDragable {</span></span>
    <span class="hljs-comment">// ...</span>
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1673716866485/b8e643b9-73db-4358-916e-551f846c675e.png" alt class="image--center mx-auto" /></p>
<p>Coming to the nullable references, each type has its nullable counterpart which is a supertype for the type. For example, <code>Unit</code> is a subtype of <code>Unit?</code> .</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1673717047737/ff7ec63e-9c6b-4449-886f-faf9088776ec.png" alt class="image--center mx-auto" /></p>
<p>Expanding the complete graph to include nullable types results in the following</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1673717537473/d3958c4b-8c89-451e-a92a-42cd2d250264.png" alt class="image--center mx-auto" /></p>
<p>Now, at the "bottom" of the type hierarchy is the <code>Nothing</code> type. So here's the complete type hierarchy in Kotlin.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1673717709431/039a229e-fc42-4172-a209-2db2571ab374.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-working-with-nullable-types">Working with Nullable Types</h2>
<p>As we saw that we cannot directly access the properties and methods of nullable types, hence it's a bit tricky to work with them. There are two very useful operators to work with nullable types - safe call operator <code>?</code> and Elvis operator <code>?:</code>.</p>
<p>Let's first see how the safe-call operator works. This operator returns null if the operand is null. Hence, it allows you to access properties and methods of nullable variables without the risk of Null Pointer Exception.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">var</span> name: String? = <span class="hljs-string">"John"</span>
<span class="hljs-keyword">var</span> firstChar = name?.<span class="hljs-keyword">get</span>(<span class="hljs-number">0</span>) <span class="hljs-comment">// Evaluates to J</span>

name = <span class="hljs-literal">null</span>
firstChar = name?.<span class="hljs-keyword">get</span>(<span class="hljs-number">0</span>) <span class="hljs-comment">// Evaluates to null</span>
</code></pre>
<p>In this example, if the <code>name</code> variable is <code>null</code>, <code>null</code> will be assigned to the <code>firstChar</code> variable.</p>
<p>Now, let's take a look at the Elvis operator (<code>?:</code>). It is similar to an if-else statement, like so:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> name: String? = <span class="hljs-string">"John"</span>
<span class="hljs-keyword">val</span> firstChar = name?.<span class="hljs-keyword">get</span>(<span class="hljs-number">0</span>) ?: <span class="hljs-string">'?'</span>
</code></pre>
<p>This is the same as writing:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> name: String? = <span class="hljs-string">"John"</span>
<span class="hljs-keyword">val</span> firstChar = <span class="hljs-keyword">if</span>(name != <span class="hljs-literal">null</span>) name.<span class="hljs-keyword">get</span>(<span class="hljs-number">0</span>) <span class="hljs-keyword">else</span> <span class="hljs-string">'?'</span>
</code></pre>
<p>One more way to handle nullable variables is the not-null assertion operator (<code>!!</code>). It is used to explicitly assert that a nullable type is not null, and this will throw a null pointer exception if it is. We can use this operator when we are sure that a nullable variable holds a non-null value. For example:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> name: String? = <span class="hljs-string">"John"</span>
<span class="hljs-keyword">val</span> upperCaseName = name!!.toUpperCase()
</code></pre>
<h2 id="heading-type-checks-and-casts">Type checks and casts</h2>
<h3 id="heading-is-operator"><code>is</code> operator</h3>
<p>In Kotlin, we can check the type of an object using the <code>is</code> operator and its negated form <code>!is</code>. These operators perform a runtime check that identifies whether an object conforms to a given type.</p>
<p>For example, if we have an object <code>obj</code> and want to check if it's of type <code>String</code>, we can do the following:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">if</span> (obj <span class="hljs-keyword">is</span> String) {
    print(obj.length)
}

<span class="hljs-comment">// OR</span>

<span class="hljs-keyword">if</span> (obj !<span class="hljs-keyword">is</span> String) { <span class="hljs-comment">// same as !(obj is String)</span>
    print(<span class="hljs-string">"Not a String"</span>)
} <span class="hljs-keyword">else</span> {
    print(obj.length)
}
</code></pre>
<h3 id="heading-as-and-asoperator"><code>as</code> and <code>as?</code>operator</h3>
<p>Kotlin offers two types of cast operators that can be used to change the type of the object. The first is the unsafe cast operator, denoted by the keyword "as". This operator will throw an exception if the cast is not possible. For example, if we try to cast a variable of type <code>Any</code> to a <code>String</code> using the unsafe cast operator, the code will throw a <code>ClassCastException</code> if the variable is not a <code>String</code>.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> x: Any = <span class="hljs-string">"hello"</span>
<span class="hljs-keyword">val</span> y: String = x <span class="hljs-keyword">as</span> String <span class="hljs-comment">// This will work</span>
<span class="hljs-keyword">val</span> z: Any = <span class="hljs-number">123</span>
<span class="hljs-keyword">val</span> a: String = z <span class="hljs-keyword">as</span> String <span class="hljs-comment">// This will throw a ClassCastException</span>
</code></pre>
<p>The second type of cast operator is the safe cast operator, denoted by the keyword "as?". This operator will return <code>null</code> if the cast is not possible, instead of throwing an exception. This can be useful in situations where we are not sure if the variable is of the type we expect it to be.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> x: Any = <span class="hljs-string">"hello"</span>
<span class="hljs-keyword">val</span> y: String? = x <span class="hljs-keyword">as</span>? String <span class="hljs-comment">// This will return "hello"</span>
<span class="hljs-keyword">val</span> z: Any = <span class="hljs-number">123</span>
<span class="hljs-keyword">val</span> a: String? = z <span class="hljs-keyword">as</span>? String <span class="hljs-comment">// This will return null</span>
</code></pre>
<h3 id="heading-smart-cast-in-kotlin">Smart Cast in Kotlin</h3>
<p>In addition to these explicit cast operators, Kotlin also has a feature called <em>smart casts</em>. Smart casts allow the compiler to automatically insert safe casts when necessary, without the need for explicit cast operators. The compiler can track the type of a variable and insert a cast when it is used in a context where a different type is expected.</p>
<p>For example, consider the following code:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">if</span> (x <span class="hljs-keyword">is</span> String) {
    print(x.length) <span class="hljs-comment">// x is automatically cast to String</span>
}
</code></pre>
<p>Here, the compiler is smart enough to know that x will be a String in the body of if block, hence, it automatically casts the variable x to String.</p>
<p>However, it's important to note that smart casts work only when the compiler can guarantee that the variable won't change between the check and the usage. More specifically, smart casts can be used under the following conditions:</p>
<ul>
<li><p><code>val</code> local variables - always, except local delegated properties</p>
</li>
<li><p><code>val</code> properties - if the property is private or internal or if the check is performed in the same module where the property is declared. Smart casts cannot be used on open properties or properties that have custom getters.</p>
</li>
<li><p><code>var</code> local variables - if the variable is not modified between the check and the usage, is not captured in a lambda that modifies it, and is not a local delegated property.</p>
</li>
<li><p><code>var</code> properties - never, because the variable can be modified at any time by other code.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In conclusion, the Kotlin-type system is an important aspect of the language that provides many features to ensure safety and reliability in your code. We have discussed the basic types available in Kotlin, the concept of null safety, and the various type casts and checks that can be used to ensure that your code is working as expected.</p>
<p>It is important to understand how to use these features to prevent common errors such as null pointer exceptions and type mismatches. By making use of nullable types, the safe call operator, and the Elvis operator, you can write code that is safe from null references and is more readable.</p>
<p>We have also discussed how to use the <code>is</code> and <code>!is</code> operators and the safe and unsafe cast operators to perform runtime type checks and casts. Smart casts, which are automatically inserted by the compiler when necessary, provide an even more convenient way to handle types.</p>
<p>In the next article in this series, we will delve into data classes. Data classes are a special type of class in Kotlin that are designed to hold data. They are typically used to represent the data model in an app, such as a user or a product.</p>
<p>Keep Coding!</p>
]]></content:encoded></item><item><title><![CDATA[Kotlin Polymorphism and Inheritance: Essential Concepts for Android Developers]]></title><description><![CDATA[Welcome back to the third article in this series of Android Development with Kotlin and Jetpack Compose. In the previous article, we covered the fundamentals of object-oriented programming in Kotlin - including classes, properties, methods and object...]]></description><link>https://hardiksachan.com/kotlin-polymorphism-and-inheritance-essential-concepts-for-android-developers</link><guid isPermaLink="true">https://hardiksachan.com/kotlin-polymorphism-and-inheritance-essential-concepts-for-android-developers</guid><category><![CDATA[Kotlin]]></category><category><![CDATA[Android]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Object Oriented Programming]]></category><category><![CDATA[#codenewbies]]></category><dc:creator><![CDATA[Hardik Sachan]]></dc:creator><pubDate>Wed, 04 Jan 2023 17:26:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1672853003889/6860f82a-d2d4-4adb-9a6c-7cc13f2e4f73.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Welcome back to the third article in this series of Android Development with Kotlin and Jetpack Compose. In the <a target="_blank" href="https://hardiksachan.hashnode.dev/the-essential-guide-to-object-oriented-programming-in-kotlin">previous article</a>, we covered the fundamentals of object-oriented programming in Kotlin - including classes, properties, methods and objects</p>
<p>In this article, we will learn about inheritance and polymorphism, and how are these concepts useful in Android development. By the means of this article, we will also discuss interfaces and abstract classes. Let's get started!</p>
<h1 id="heading-introduction-to-inheritance-and-polymorphism">Introduction to Inheritance and polymorphism</h1>
<p>Inheritance and Polymorphism are important concepts in the object-oriented programming paradigm. Let's look at how each one is important.</p>
<h2 id="heading-inheritance">Inheritance</h2>
<p>Inheritance is a way to create new classes that are derived from existing classes. This is particularly useful because these <em>derived classes</em> have access to the properties and methods of the <em>base</em> class.</p>
<p>For instance, imagine that you are building an app for a school. You might have a class called <code>Person</code> that has information about a person, like their name and age.</p>
<p>Then, you can create new classes for specific types of people, like students and teachers. These new classes will <em>inherit</em> all the information from the <code>Person</code> class and you can add more specific information to them as well.</p>
<p>For example, the <code>Student</code> class might have information about what grade the student is in, and the <code>Teacher</code> class might have information about what subject the teacher teaches.</p>
<p>Inheritance is a useful tool in programming because it allows us to reuse code and create more specialized classes without having to write all the code from scratch. This can save us a lot of time and make our app more efficient.</p>
<h2 id="heading-polymorphism">Polymorphism</h2>
<p>Polymorphism is a way of creating objects that can take on different forms. It gives us the ability to make sure that the classes of same category conform to a similar structure.</p>
<p>Imagine that you are building an app that has different types of animals, like dogs, cats, and birds. Each type of animal has its own unique characteristics, like the way they move, the sounds they make, and the things they like to do.</p>
<p>But they also have some things in common, like the fact that they are all animals and they can make sounds - although these sounds will depend on the type of animal all animals can make sounds.</p>
<p>Polymorphism allows us to create a <em>template</em> or <em>plan</em> for an animal that includes all the things that all animals can do. Then, we can create specific implementations for each type of animal, and give them the unique characteristics that are specific to that type of animal.</p>
<p>This is useful in programming because it allows us to create code that can be used in different situations and can adapt to different types of objects. It helps us to write more efficient and flexible code.</p>
<p>So with this understanding of inheritance and polymorphism, Let's look at how we can implement them in Kotlin.</p>
<h1 id="heading-inheritance-in-kotlin">Inheritance in Kotlin</h1>
<p>As we saw earlier, <em>inheritance is the</em> practice of creating new classes by deriving them from existing classes. In Kotlin, we need to tell the compiler that we will be using a certain class to create a new class derived from it; to do this, we use the <code>open</code> keyword.</p>
<p>Imagine we are developing an application for a library. We would need a <code>Book</code> class that with properties such as <code>title</code>, <code>author</code>, and <code>isbn</code>. And we would also need a <code>Movie</code> class with properties such as <code>title</code>, <code>director</code>, and <code>releaseYear</code>.</p>
<p>Instead of having two separate classes with similar properties, we can create a parent <code>Media</code> class with the shared properties and have the <code>Book</code> and <code>Movie</code> classes inherit from it. This would allow you to reuse the shared code and keep your code organized.</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">Media</span> </span>{
    <span class="hljs-keyword">var</span> title: String = <span class="hljs-string">""</span>
    <span class="hljs-keyword">var</span> releaseYear: <span class="hljs-built_in">Int</span> = <span class="hljs-number">0</span>

    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getDescription</span><span class="hljs-params">()</span></span>: String {
        <span class="hljs-keyword">return</span> <span class="hljs-string">"<span class="hljs-variable">$title</span> (<span class="hljs-variable">$releaseYear</span>)"</span>
    }
}
</code></pre>
<p>Now, to create a class that inherits from <code>Media</code> class, place the name superclass (<code>Media</code> in this case) after <code>:</code> in the declaration of the derived class</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Book</span>: <span class="hljs-type">Media</span></span>() {
    <span class="hljs-keyword">var</span> author: String = <span class="hljs-string">""</span>
    <span class="hljs-keyword">var</span> isbn: String = <span class="hljs-string">""</span>
}
</code></pre>
<p>Similarly, here's how you can create the <code>Movie</code> class we discussed above</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Movie</span>: <span class="hljs-type">Media</span></span>() {
    <span class="hljs-keyword">var</span> director: String = <span class="hljs-string">""</span>
    <span class="hljs-keyword">var</span> runtime: <span class="hljs-built_in">Int</span> = <span class="hljs-number">0</span>
}
</code></pre>
<h2 id="heading-overriding-methods">Overriding methods</h2>
<p>Now that we have specialized classes for Books and Movies, we will need to make their descriptions a little more specific. For that, we will override the <code>getDescription</code> method.</p>
<p>To make a method <em>overridable</em>, we need to mark it with <code>open</code> keyword as we did with classes</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">Media</span> </span>{
    <span class="hljs-keyword">var</span> title: String = <span class="hljs-string">""</span>
    <span class="hljs-keyword">var</span> releaseYear: <span class="hljs-built_in">Int</span> = <span class="hljs-number">0</span>

    <span class="hljs-keyword">open</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getDescription</span><span class="hljs-params">()</span></span>: String {
        <span class="hljs-keyword">return</span> <span class="hljs-string">"<span class="hljs-variable">$title</span> (<span class="hljs-variable">$releaseYear</span>)"</span>
    }
}
</code></pre>
<p>Now, we will add the specialized method in the child classes.</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Book</span>: <span class="hljs-type">Media</span></span>() {
    <span class="hljs-keyword">var</span> author: String = <span class="hljs-string">""</span>
    <span class="hljs-keyword">var</span> isbn: String = <span class="hljs-string">""</span>

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getDescription</span><span class="hljs-params">()</span></span>: String {
        <span class="hljs-keyword">return</span> <span class="hljs-string">"<span class="hljs-variable">$title</span> by <span class="hljs-variable">$author</span> (<span class="hljs-variable">$releaseYear</span>) [ISBN: <span class="hljs-variable">$isbn</span>]"</span>
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Movie</span>: <span class="hljs-type">Media</span></span>() {
    <span class="hljs-keyword">var</span> director: String = <span class="hljs-string">""</span>
    <span class="hljs-keyword">var</span> runtime: <span class="hljs-built_in">Int</span> = <span class="hljs-number">0</span>

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getDescription</span><span class="hljs-params">()</span></span>: String {
        <span class="hljs-keyword">return</span> <span class="hljs-string">"<span class="hljs-variable">$title</span> directed by <span class="hljs-variable">$director</span> (<span class="hljs-variable">$releaseYear</span>, <span class="hljs-variable">$runtime</span> minutes)"</span>
    }
}
</code></pre>
<h1 id="heading-polymorphism-in-kotlin">Polymorphism in Kotlin</h1>
<p>As we saw earlier, <em>polymorphism is the</em> practice of creating objects that can take on different forms. To do this, we can use a <em>normal class</em>, an <em>abstract class</em>, or an <em>interface</em> as the base and build specific implementations by deriving from them.</p>
<p>Let's go with the example of different animals from above. Imagine that you are building an app that has different types of animals, like dogs, cats, and birds. Each type of animal has its unique characteristics, like the way they move, the sounds they make, and the things they like to do.</p>
<p>In this situation, we could use polymorphism to create a base <code>Animal</code> class with shared properties and behaviors, and then create subclasses for each specific type of animal. This would allow us to define the unique characteristics of each animal in the subclass, while still being able to treat them all as <code>Animal</code> objects.</p>
<p>Let's see how we can implement this code by first using abstract classes and then by using interfaces.</p>
<h2 id="heading-using-abstract-classes-for-polymorphisms">Using Abstract Classes for Polymorphisms</h2>
<p>As per Kotlin docs,</p>
<blockquote>
<p>A class may be declared <code>abstract</code>, along with some or all of its members. An abstract member does not have an implementation in its class. You don't need to annotate abstract classes or functions with <code>open</code>.</p>
</blockquote>
<p>Here's how we would implement the base <code>Animal</code> class as an abstract class</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>{
    <span class="hljs-keyword">var</span> name: String = <span class="hljs-string">""</span>

    <span class="hljs-keyword">abstract</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">move</span><span class="hljs-params">()</span></span>: String
    <span class="hljs-keyword">abstract</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">speak</span><span class="hljs-params">()</span></span>: String
}
</code></pre>
<p>Since the class is abstract, we don't need to implement the methods <code>move</code> and <code>speak</code>. Now, let's create our specialized animal classes from this.</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span>: <span class="hljs-type">Animal</span></span>() {
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">move</span><span class="hljs-params">()</span></span>: String {
        <span class="hljs-keyword">return</span> <span class="hljs-string">"<span class="hljs-variable">$name</span> the dog is running and playing."</span>
    }

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">speak</span><span class="hljs-params">()</span></span>: String {
        <span class="hljs-keyword">return</span> <span class="hljs-string">"<span class="hljs-variable">$name</span> the dog is barking."</span>
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Cat</span>: <span class="hljs-type">Animal</span></span>() {
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">move</span><span class="hljs-params">()</span></span>: String {
        <span class="hljs-keyword">return</span> <span class="hljs-string">"<span class="hljs-variable">$name</span> the cat is stalking its prey."</span>
    }

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">speak</span><span class="hljs-params">()</span></span>: String {
        <span class="hljs-keyword">return</span> <span class="hljs-string">"<span class="hljs-variable">$name</span> the cat is meowing."</span>
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bird</span>: <span class="hljs-type">Animal</span></span>() {
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">move</span><span class="hljs-params">()</span></span>: String {
        <span class="hljs-keyword">return</span> <span class="hljs-string">"<span class="hljs-variable">$name</span> the bird is flying."</span>
    }

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">speak</span><span class="hljs-params">()</span></span>: String {
        <span class="hljs-keyword">return</span> <span class="hljs-string">"<span class="hljs-variable">$name</span> the bird is chirping."</span>
    }
}
</code></pre>
<h2 id="heading-using-interfaces-for-polymorphism">Using Interfaces for Polymorphism</h2>
<p>Interfaces in Kotlin are used to define a set of <em>abstract methods</em> that must be implemented by a class that wants to implement the interface. Interfaces are similar to abstract classes, but they can only contain abstract methods and cannot contain any concrete methods with an implementation. We can also have properties in interfaces but they will only have the getter when accessed as an interface</p>
<p>Here is how we can define an Animal as an interface instead of <em>an abstract class.</em></p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">IAnimal</span> </span>{
    <span class="hljs-keyword">val</span> name: String

    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">move</span><span class="hljs-params">()</span></span>: String
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">speak</span><span class="hljs-params">()</span></span>: String
}
</code></pre>
<p>Now to create a concrete implementation of the above interface we will need to override <code>move</code>, <code>speak</code> and <code>name</code>. Here's how we can implement the above animals using interfaces:</p>
<pre><code class="lang-kotlin">
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> </span>(
    <span class="hljs-keyword">override</span> <span class="hljs-keyword">val</span> name: String
): IAnimal {
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">move</span><span class="hljs-params">()</span></span>: String {
        <span class="hljs-keyword">return</span> <span class="hljs-string">"<span class="hljs-variable">$name</span> the dog is running and playing."</span>
    }

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">speak</span><span class="hljs-params">()</span></span>: String {
        <span class="hljs-keyword">return</span> <span class="hljs-string">"<span class="hljs-variable">$name</span> the dog is barking."</span>
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Cat</span></span>(
    <span class="hljs-keyword">override</span> <span class="hljs-keyword">val</span> name: String
): IAnimal {
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">move</span><span class="hljs-params">()</span></span>: String {
        <span class="hljs-keyword">return</span> <span class="hljs-string">"<span class="hljs-variable">$name</span> the cat is stalking its prey."</span>
    }

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">speak</span><span class="hljs-params">()</span></span>: String {
        <span class="hljs-keyword">return</span> <span class="hljs-string">"<span class="hljs-variable">$name</span> the cat is meowing."</span>
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bird</span></span>(
    <span class="hljs-keyword">override</span> <span class="hljs-keyword">val</span> name: String
): IAnimal {
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">move</span><span class="hljs-params">()</span></span>: String {
        <span class="hljs-keyword">return</span> <span class="hljs-string">"<span class="hljs-variable">$name</span> the bird is flying."</span>
    }

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">speak</span><span class="hljs-params">()</span></span>: String {
        <span class="hljs-keyword">return</span> <span class="hljs-string">"<span class="hljs-variable">$name</span> the bird is chirping."</span>
    }
}
</code></pre>
<h2 id="heading-benefit-of-polymorphism">Benefit of polymorphism</h2>
<p>Now, the main benefit of polymorphism is ability to change form in runtime. Here's a sample of polymorphism in action</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> animals: List&lt;IAnimal&gt; = listOf(
        Dog(<span class="hljs-string">"Henry"</span>),
        Cat(<span class="hljs-string">"Tom"</span>),
        Bird(<span class="hljs-string">"Bubbles"</span>)
    )

    <span class="hljs-keyword">for</span> (animal <span class="hljs-keyword">in</span> animals) {
        println(animal.speak())
    }
}
</code></pre>
<p>The above code outputs:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672852287259/24298df6-fe5a-4b60-abde-22ed672687a3.png" alt class="image--center mx-auto" /></p>
<p>As you can see we declared all the creatures with the type <code>IAnimal</code> but during runtime, they conform to their specific types i.e <code>Dog</code>, <code>Cat</code> and <code>Bird</code></p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>In conclusion, polymorphism and inheritance are important concepts in object-oriented programming languages like Kotlin. Polymorphism allows for flexibility and code reuse, as a single class can take on multiple forms and behave differently in different situations. Inheritance allows for the creation of new classes that are derived from existing ones, allowing for code reuse and organization.</p>
<p>Together, polymorphism and inheritance can be used to create complex and flexible object-oriented systems, making it easier to manage and maintain code. Developers need to understand these concepts and know how to use them effectively when designing and building applications.</p>
<p>Keep Coding!</p>
]]></content:encoded></item><item><title><![CDATA[The Essential Guide to Object-Oriented Programming in Kotlin]]></title><description><![CDATA[Introduction
In the previous article, we learned the foundations of object-oriented programming with Kotlin. We set up our development environment, installed Android Studio and the Android SDK, and explored the basic syntax of Kotlin, including varia...]]></description><link>https://hardiksachan.com/the-essential-guide-to-object-oriented-programming-in-kotlin</link><guid isPermaLink="true">https://hardiksachan.com/the-essential-guide-to-object-oriented-programming-in-kotlin</guid><category><![CDATA[Android]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Object Oriented Programming]]></category><category><![CDATA[basics]]></category><dc:creator><![CDATA[Hardik Sachan]]></dc:creator><pubDate>Sun, 01 Jan 2023 07:47:31 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1672559158448/85a47ac4-929c-4fc7-bc58-f25b9ae25c07.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>In the <a target="_blank" href="https://hardiksachan.hashnode.dev/getting-started-with-kotlin">previous article</a>, we learned the foundations of object-oriented programming with Kotlin. We set up our development environment, installed Android Studio and the Android SDK, and explored the basic syntax of Kotlin, including variable declarations, data types, control flow, and defining and calling functions.</p>
<p>Now, we're ready to take our understanding of Kotlin a step further by exploring the basics of object-oriented programming in Kotlin. This article will go over how to define and use classes and objects in Kotlin, including constructors, properties, and methods.</p>
<p>But, before we get into the specifics, let's define exactly what we mean by "classes" and "objects."</p>
<h3 id="heading-what-are-classes-and-objects">What are classes and objects?</h3>
<p>A class is a template that specifies the properties and behavior of a specific type of object. A class can have both properties (variables that store data) and methods (functions that perform actions).</p>
<p>An object is a class instance. When you create an object, you are essentially creating a specific instance of a class, complete with its own set of properties and methods. You can make multiple objects from the same class, each with its own set of properties and behaviors.</p>
<p>Classes and objects are useful for organizing and encapsulating code, as well as creating reusable components that can be reused throughout a program. They are a necessary tool for developing complex software applications.</p>
<p>Now that we've covered the fundamentals of classes and objects, let's look at why they are important for you as an android developer.</p>
<h3 id="heading-why-are-classes-and-objects-important-for-android-development">Why are classes and objects important for Android development?</h3>
<p>As an Android developer, learning how to define and use classes and objects is essential for building efficient, maintainable, and scalable Android apps. Here are a few reasons why:</p>
<ul>
<li><p><strong>Organization and structure:</strong> Classes and objects enable you to break down your code into logical units that are easier to understand and work with. This can assist you in writing more organized and maintainable code, particularly as your projects grow larger and more complex.</p>
</li>
<li><p><strong>Reusability:</strong> You can create reusable components that can be used in different parts of your app by defining classes and objects. You will save time and effort because you will not have to rewrite the same code over and over.</p>
</li>
<li><p><strong>Modularity:</strong> Classes and objects allow you to divide your code into self-contained units that can be tested and debugged independently. This can help you identify and fix bugs in your code, as well as add new features and functionality.</p>
</li>
</ul>
<p>Overall, understanding classes and objects is an important step toward becoming a skilled Android developer. In the sections that follow, we'll look at how to define and use classes and objects in Kotlin so that you can use them in your Android projects.</p>
<h2 id="heading-defining-a-class-in-kotlin">Defining <strong>a class in Kotlin</strong></h2>
<p>In Kotlin, you can define a class by using the <code>class</code> keyword followed by the class name. For example, you could define a class called <code>Person</code> like this:</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-comment">// class body</span>
}
</code></pre>
<p>In the following sections, we'll look at how you can define the properties and methods of the class inside the class body.</p>
<p>You can also define a class with a primary constructor, which allows you to initialize the class with specific values when creating an object from it. We'll go over primary constructors in greater depth later in the article.</p>
<h3 id="heading-defining-class-properties">Defining class properties</h3>
<p>You can define the class's properties within the class body by using the <code>val</code> or <code>var</code> keyword, followed by the property name and type. For example, you could define a <code>String</code> property called <code>name</code> as follows:</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
}
</code></pre>
<p>You can also provide an initial value for the property by assigning it to a default value in the constructor. For 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">val</span> name: String = <span class="hljs-string">""</span>) {
    <span class="hljs-comment">// class body</span>
}
</code></pre>
<p>The name property is declared as a <code>val</code> in this instance, making it a read-only property that cannot be modified after initialization. Use the <code>var</code> keyword in its place to define a property that can be modified:</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> age: <span class="hljs-built_in">Int</span>
}
</code></pre>
<p>Properties in Kotlin are <code>public</code> by default, which means they can be accessed and modified from anywhere within the class and from outside the class. You can, however, use visibility modifiers to control the visibility and accessibility of your properties.</p>
<p>Here are the four visibility modifiers in Kotlin:</p>
<ul>
<li><code>private</code>: A <code>private</code> property can only be accessed and modified within the class in which it's defined.</li>
</ul>
<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">private</span> <span class="hljs-keyword">val</span> name: String
}
</code></pre>
<ul>
<li><code>protected</code>: A <code>protected</code> property can only be accessed and modified within the class in which it is defined and any subclasses of that class.</li>
</ul>
<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">protected</span> <span class="hljs-keyword">val</span> name: String
}
</code></pre>
<ul>
<li><code>internal</code>: An <code>internal</code> property can be accessed and modified from anywhere within the same module (i.e. a set of compiled Kotlin files).</li>
</ul>
<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">internal</span> <span class="hljs-keyword">val</span> name: String
}
</code></pre>
<ul>
<li><code>public</code>: A <code>public</code> property can be accessed and modified from anywhere within the class as well as from outside the class. This is the <strong>default visibility</strong> in Kotlin.</li>
</ul>
<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">public</span> <span class="hljs-keyword">val</span> name: String
}
</code></pre>
<p>You can control who can access and modify your properties by using visibility modifiers, which can help you write more secure and maintainable code.</p>
<h3 id="heading-defining-class-methods">Defining class methods</h3>
<p>In addition to properties, methods can also be defined in a Kotlin class. A method is a function that executes a specific action and may or may not return a value.</p>
<p>In Kotlin, you define a method by using the <code>fun</code> keyword, followed by the method name, any arguments, and the return type (if applicable). For example, in the <code>Person</code> class, you could define a <code>greet</code> method that takes a <code>name</code> argument of type <code>String</code> and returns a <code>String</code>:</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-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>: String {
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Hello, <span class="hljs-variable">$name</span>!"</span>
    }
}
</code></pre>
<p>You can also define methods that don't have any arguments or return values:</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-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">sayHello</span><span class="hljs-params">()</span></span> {
        println(<span class="hljs-string">"Hello!"</span>)
    }
}
</code></pre>
<p>Or you can define methods with default values for their arguments, which allows you to call the method with fewer arguments:</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-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 class="hljs-string">"stranger"</span>)</span></span>: String {
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Hello, <span class="hljs-variable">$name</span>!"</span>
    }
}
</code></pre>
<p>Methods in Kotlin, like properties, are <code>public</code> by default, which means they can be called from anywhere within and outside the class. However, just like with properties, you can use visibility modifiers to control the visibility and accessibility of your methods.</p>
<p>We'll look at how to create objects from classes and use their properties and methods in the following section.</p>
<h2 id="heading-creating-objects">Creating objects</h2>
<p>Now that we've gone over how to define classes, as well as their properties and methods, let's look at how to create objects from those classes.</p>
<p>You can create an object from a class in Kotlin by simply calling the class name with any necessary arguments. The basic syntax is as follows:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> obj = Person()
</code></pre>
<p>This will create a new object from the <code>Person</code> class and assign it to the <code>obj</code> variable. You can then access the object's properties and methods using the <code>.</code> operator:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> obj = Person()
<span class="hljs-keyword">val</span> name = obj.name  <span class="hljs-comment">// access the 'name' property</span>
obj.sayHello()       <span class="hljs-comment">// call the 'sayHello' method</span>
</code></pre>
<p>If the class has a primary constructor, you can pass in arguments when you create the object to initialize its properties. For 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">val</span> name: String, <span class="hljs-keyword">var</span> age: <span class="hljs-built_in">Int</span>) {
    <span class="hljs-comment">// class body</span>
}

<span class="hljs-keyword">val</span> obj = Person(<span class="hljs-string">"Alice"</span>, <span class="hljs-number">25</span>)
</code></pre>
<p>This creates a new <code>Person</code> object with the name "Alice" and age 25.</p>
<p>In the next section, we'll take a closer look at primary constructors and how to define them in Kotlin.</p>
<h2 id="heading-constructors">Constructors</h2>
<h3 id="heading-defining-a-primary-constructor">Defining a primary constructor</h3>
<p>To define a primary constructor for a class in Kotlin, use the <code>constructor</code> keyword. A primary constructor is a type of constructor that allows you to initialize a class with specific values when creating an object from it.</p>
<p>The <code>constructor</code> keyword is followed by any necessary arguments and the class body to define a primary constructor. For the <code>Person</code> class, for example, you could define a primary constructor that accepts a <code>name</code> and an <code>age</code> argument:</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> <span class="hljs-keyword">constructor</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-comment">// class body</span>
}
</code></pre>
<p>This primary constructor allows you to initialize the <code>name</code> and <code>age</code> properties of the <code>Person</code> class when you create an object from it:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> obj = Person(<span class="hljs-string">"Alice"</span>, <span class="hljs-number">25</span>)
</code></pre>
<p>It's also possible to define a primary constructor with default values for its arguments, which allows you to create objects with fewer arguments:</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> <span class="hljs-keyword">constructor</span></span>(<span class="hljs-keyword">val</span> name: String = <span class="hljs-string">""</span>, <span class="hljs-keyword">var</span> age: <span class="hljs-built_in">Int</span> = <span class="hljs-number">0</span>) {
    <span class="hljs-comment">// class body</span>
}

<span class="hljs-keyword">val</span> obj1 = Person()      <span class="hljs-comment">// name = "", age = 0</span>
<span class="hljs-keyword">val</span> obj2 = Person(<span class="hljs-string">"Bob"</span>) <span class="hljs-comment">// name = "Bob", age = 0</span>
</code></pre>
<p>In the next section, we'll take a look at how to define and use secondary constructors in Kotlin.</p>
<h3 id="heading-defining-secondary-constructors">Defining secondary constructors</h3>
<p>Kotlin allows you to define secondary constructors for your classes in addition to primary constructors. A secondary constructor is defined in addition to the primary constructor and allows you to initialize the class in various ways.</p>
<p>The <code>constructor</code> keyword is followed by any necessary arguments and the class body to define a secondary constructor. For example, for the Person class, you could define a secondary constructor that takes a <code>name</code> argument and sets the <code>age</code> property to a default value:</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">constructor</span>(name: String) : <span class="hljs-keyword">this</span>(name, <span class="hljs-number">0</span>) {
        <span class="hljs-comment">// constructor body</span>
    }
}
</code></pre>
<p>This secondary constructor allows you to create a new <code>Person</code> object with just the <code>name</code> property initialized:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> obj = Person(<span class="hljs-string">"Alice"</span>)
</code></pre>
<p>It's also possible to define multiple secondary constructors, each with its own set of arguments and initialization logic. For 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">val</span> name: String, <span class="hljs-keyword">var</span> age: <span class="hljs-built_in">Int</span>) {
    <span class="hljs-keyword">constructor</span>(name: String) : <span class="hljs-keyword">this</span>(name, <span class="hljs-number">0</span>) {
        <span class="hljs-comment">// constructor body</span>
    }

    <span class="hljs-keyword">constructor</span>(age: <span class="hljs-built_in">Int</span>) : <span class="hljs-keyword">this</span>(<span class="hljs-string">""</span>, age) {
        <span class="hljs-comment">// constructor body</span>
    }
}

<span class="hljs-keyword">val</span> obj1 = Person(<span class="hljs-string">"Alice"</span>) <span class="hljs-comment">// name = "Alice", age = 0</span>
<span class="hljs-keyword">val</span> obj2 = Person(<span class="hljs-number">25</span>)      <span class="hljs-comment">// name = "", age = 25</span>
</code></pre>
<p>Secondary constructors are useful when you want to provide multiple ways for your class to be initialized based on the data you have available.</p>
<p>In the following section, we'll look at how to use properties and methods from inside as well as outside the class.</p>
<h2 id="heading-using-class-properties-and-methods">Using class properties and methods</h2>
<p>Now that we've covered how to define classes, their properties, and methods, let's look at how to use them both within and outside of the class.</p>
<h3 id="heading-using-class-properties-and-methods-within-the-class">Using <strong>class properties and methods within the class</strong></h3>
<p>To use a class property or method within the class, simply type <code>this</code> keyword followed by the name of the property or method. 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">val</span> name: String, <span class="hljs-keyword">var</span> age: <span class="hljs-built_in">Int</span>) {
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">sayHello</span><span class="hljs-params">()</span></span> {
        println(<span class="hljs-string">"Hello, my name is <span class="hljs-subst">${this.name}</span> and I am <span class="hljs-subst">${this.age}</span> years old."</span>)
    }
}
</code></pre>
<p>In this example, the <code>sayHello</code> method uses the <code>this.name</code> and <code>this.age</code> properties to print a greeting.</p>
<h3 id="heading-using-class-properties-and-methods-from-outside-the-class">Using <strong>class properties and methods from outside the class</strong></h3>
<p>To use a class property or method from outside the class, you use the <code>.</code> operator followed by the property or method name. Here's an example:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> obj = Person(<span class="hljs-string">"Alice"</span>, <span class="hljs-number">25</span>)
<span class="hljs-keyword">val</span> name = obj.name  <span class="hljs-comment">// access the 'name' property</span>
obj.sayHello()       <span class="hljs-comment">// call the 'sayHello' method</span>
</code></pre>
<p>In this example, the <code>obj</code> variable is an object from the <code>Person</code> class, and the <code>name</code> and <code>sayHello</code> properties and methods are accessed using the <code>.</code> operator.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>We've now covered the fundamentals of Kotlin classes and objects! We've learned how to define classes, as well as their primary and secondary constructors, as well as how to create objects from those classes and use class properties and methods.</p>
<p>In the next article in this series, we'll delve even deeper into the world of Kotlin by looking at inheritance and polymorphism. We'll see how to use abstract classes and interfaces to define common methods and properties that can be implemented by multiple classes, as well as how to use polymorphism to allow objects to change forms at runtime.</p>
<p>Stay tuned for more exciting adventures in Android development with Kotlin!</p>
]]></content:encoded></item><item><title><![CDATA[Getting started with Kotlin]]></title><description><![CDATA[Welcome to the world of Kotlin! If you're an Android developer, chances are you've already heard a thing or two about this amazing programming language. But if you're new to Kotlin, don't worry – we're here to help.
In this article, we'll be introduc...]]></description><link>https://hardiksachan.com/getting-started-with-kotlin</link><guid isPermaLink="true">https://hardiksachan.com/getting-started-with-kotlin</guid><category><![CDATA[Android]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[Android Studio]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[learning]]></category><dc:creator><![CDATA[Hardik Sachan]]></dc:creator><pubDate>Sat, 31 Dec 2022 09:34:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1672560115189/bb64d29d-2dfa-41db-9bf3-573f6e5f7a62.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Welcome to the world of Kotlin! If you're an Android developer, chances are you've already heard a thing or two about this amazing programming language. But if you're new to Kotlin, don't worry – we're here to help.</p>
<p>In this article, we'll be introducing you to the basics of Kotlin and getting you set up for success in your Android development journey. We'll cover everything from setting up your development environment to learning the ins and outs of Kotlin syntax.</p>
<p>But before we dive in, let's talk about why Kotlin is such an important language for Android developers. Simply put, Kotlin is a modern, powerful language that makes it easy to build beautiful, efficient apps. It's concise, expressive, and fully interoperable with Java, which means you can use it alongside your existing Java code. Plus, it's been officially supported by Google as a first-class language for Android development since 2017, so you can be confident that it's here to stay.</p>
<p>So, are you ready to take the first step toward becoming a Kotlin pro? Great! Let's get started.</p>
<h2 id="heading-setting-up-the-development-environment">Setting up the development environment</h2>
<p>Before we can start writing Kotlin code, we need to set up our development environment. Here's what you'll need:</p>
<ul>
<li><p>A computer with an operating system that supports Android development, such as Windows, macOS, or Linux</p>
</li>
<li><p>The Android Studio IDE (Integrated Development Environment)</p>
</li>
<li><p>The Android SDK (Software Development Kit)</p>
</li>
</ul>
<h3 id="heading-installing-android-studio">Installing Android Studio</h3>
<p>First, let's install Android Studio. Here's how:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672475133002/80a7e21f-fddd-4984-8fe5-51c59acdbb79.png" alt class="image--center mx-auto" /></p>
<ol>
<li><p>Go to the Android Studio website (<a target="_blank" href="https://developer.android.com/studio"><strong>https://developer.android.com/studio</strong></a>)</p>
</li>
<li><p>Click the "Download Android Studio" button</p>
</li>
<li><p>Follow the prompts to install Android Studio on your computer</p>
</li>
</ol>
<p>Once the installation is complete, you can open Android Studio by double-clicking the icon on your desktop or finding it in your start menu (on Windows) or applications folder (on macOS).</p>
<h3 id="heading-installing-the-android-sdk">Installing the Android SDK</h3>
<p>The Android SDK is a collection of tools that you'll need to build Android apps. It includes everything from the Android operating system to a variety of libraries and tools that you can use to develop your apps.</p>
<p>To install the Android SDK:</p>
<ol>
<li><p>Open Android Studio</p>
</li>
<li><p>Click on the "Welcome to Android Studio" screen</p>
</li>
<li><p>Click the "Install SDK Platforms" button</p>
</li>
<li><p>Select the latest versions of the Android operating system and the Google Play system image, and click "Apply"</p>
</li>
<li><p>Click the "Install Build Tools" button</p>
</li>
<li><p>Select the latest version of the Android build tools and click "Apply"</p>
</li>
</ol>
<p>That's it! You're now ready to start developing Android apps with Kotlin. In the next section, we'll cover the basics of Kotlin syntax.</p>
<h2 id="heading-basic-kotlin-syntax">Basic Kotlin Syntax</h2>
<p>Now that we have our development environment set up, it's time to start learning some Kotlin! If you're familiar with other programming languages, you'll find that Kotlin is easy to pick up. But even if you're new to programming, don't worry – we'll go over everything step by step.</p>
<h3 id="heading-variable-declarations">Variable declarations</h3>
<p>In Kotlin, you can use the <code>var</code> keyword to declare a mutable variable, and the <code>val</code> keyword to declare an immutable variable. Here's an example:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">var</span> greeting = <span class="hljs-string">"Hello"</span>
greeting = <span class="hljs-string">"Hi"</span> <span class="hljs-comment">// this is allowed</span>

<span class="hljs-keyword">val</span> answer = <span class="hljs-number">42</span>
answer = <span class="hljs-number">43</span> <span class="hljs-comment">// this is not allowed</span>
</code></pre>
<h3 id="heading-data-types">Data types</h3>
<p>In Kotlin, you don't have to specify the type of a variable – the compiler can usually infer it from the value you assign to it. But you can also specify the type if you want to be explicit. Here are some of the basic data types in Kotlin:</p>
<ul>
<li><p><code>Int</code>: for whole numbers</p>
</li>
<li><p><code>Double</code>: for numbers with decimal points</p>
</li>
<li><p><code>String</code>: for text</p>
</li>
<li><p><code>Boolean</code>: for true/false values</p>
</li>
</ul>
<p>Here's an example of declaring variables with different data types:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> i = <span class="hljs-number">42</span> <span class="hljs-comment">// inferred as Int</span>
<span class="hljs-keyword">val</span> d = <span class="hljs-number">3.14</span> <span class="hljs-comment">// inferred as Double</span>
<span class="hljs-keyword">val</span> s = <span class="hljs-string">"Hello"</span> <span class="hljs-comment">// inferred as String</span>
<span class="hljs-keyword">val</span> b = <span class="hljs-literal">true</span> <span class="hljs-comment">// inferred as Boolean</span>
</code></pre>
<blockquote>
<p>Please note that each of the above data types has a nullable counterpart. But we will discuss nullability in Kotlin in a future article.</p>
</blockquote>
<h3 id="heading-string-templates">String Templates</h3>
<p>Kotlin provides string templates as a way to embed expressions within string literals. String templates start with a dollar sign (<code>$</code>) and can contain either a simple name or an expression in curly braces.</p>
<p>Here is an example of using a string template to print out a message:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> name = <span class="hljs-string">"John"</span>
println(<span class="hljs-string">"Hello, <span class="hljs-variable">$name</span>!"</span>) <span class="hljs-comment">// Hello, John!</span>
</code></pre>
<p>In addition to simple names, string templates can also contain expressions. The expression is evaluated and its result is converted to a string and inserted into the string. Here is an example of using an expression in a string template:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> a = <span class="hljs-number">10</span>
<span class="hljs-keyword">val</span> b = <span class="hljs-number">20</span>
println(<span class="hljs-string">"The sum of <span class="hljs-variable">$a</span> and <span class="hljs-variable">$b</span> is <span class="hljs-subst">${a + b}</span>."</span>) 
<span class="hljs-comment">// The above line outputs:</span>
<span class="hljs-comment">// The sum of 10 and 20 is 30.</span>
</code></pre>
<p>String templates are a useful feature of Kotlin that can make it easier to build strings that contain dynamic content. They can be used in a variety of contexts, such as when constructing <strong>SQL queries</strong> or building <strong>user interfaces</strong>.</p>
<h3 id="heading-conditionals">Conditionals</h3>
<p>In Kotlin, you can use conditional statements such as <code>if-else</code> and <code>when</code> to execute code based on certain conditions. Here's an example of an <code>if-else</code> statement:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> num = <span class="hljs-number">42</span>
<span class="hljs-keyword">if</span> (num % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>) {
    println(<span class="hljs-string">"Even"</span>)
} <span class="hljs-keyword">else</span> {
    println(<span class="hljs-string">"Odd"</span>)
}
</code></pre>
<p>And here's an example of a <code>when</code> statement:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> fruit = <span class="hljs-string">"apple"</span>
<span class="hljs-keyword">when</span> (fruit) {
    <span class="hljs-string">"apple"</span> -&gt; println(<span class="hljs-string">"red"</span>)
    <span class="hljs-string">"banana"</span> -&gt; println(<span class="hljs-string">"yellow"</span>)
    <span class="hljs-keyword">else</span> -&gt; println(<span class="hljs-string">"unknown"</span>)
}
</code></pre>
<h3 id="heading-loops">Loops</h3>
<p>Kotlin has a variety of loops that can be used to execute a block of code multiple times.</p>
<p>The <code>for</code> loop is used to iterate over a range of values or an array. Here is an example of using a <code>for</code> loop to print out the numbers from 1 to 10:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">for</span> (i <span class="hljs-keyword">in</span> <span class="hljs-number">1</span>..<span class="hljs-number">10</span>) {
    println(i)
}
</code></pre>
<blockquote>
<p>In the above piece of code, <code>1..10</code> is a range, it returns a list of numbers (well, kind of) from 1 to 10. We'll learn more about ranges in a future article.</p>
</blockquote>
<p>The <code>while</code> loop is used to execute a block of code as long as a certain condition is true. Here is an example of using a <code>while</code> loop to print out the numbers from 1 to 10:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">var</span> i = <span class="hljs-number">1</span>
<span class="hljs-keyword">while</span> (i &lt;= <span class="hljs-number">10</span>) {
    println(i)
    i++
}
</code></pre>
<p>The <code>do-while</code> loop is similar to the <code>while</code> loop, but the block of code is always executed at least once. Here is an example of using a <code>do-while</code> loop to print out the numbers from 1 to 10:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">var</span> i = <span class="hljs-number">1</span>
<span class="hljs-keyword">do</span> {
    println(i)
    i++
} <span class="hljs-keyword">while</span> (i &lt;= <span class="hljs-number">10</span>)
</code></pre>
<p>Kotlin also has a <code>forEach</code> loop that can be used to iterate over the elements of a collection. Here is an example of using a <code>forEach</code> loop to print out the elements of a list:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> list = listOf(<span class="hljs-string">"apple"</span>, <span class="hljs-string">"banana"</span>, <span class="hljs-string">"cherry"</span>)
list.forEach { println(it) }
</code></pre>
<p>In addition to these loops, Kotlin also has the <code>break</code> and <code>continue</code> statements, which can be used to exit a loop early or skip to the next iteration of the loop, respectively.</p>
<p>That's just a taste of the basics of Kotlin syntax. In the next section, we'll look at how to define and call functions in Kotlin.</p>
<h3 id="heading-kotlin-functions">Kotlin Functions</h3>
<p>In Kotlin, you can use functions to organize your code and reuse it throughout your app. Here's how to define and call functions in Kotlin:</p>
<p><strong>Defining functions</strong></p>
<p>To define a function in Kotlin, you use the <code>fun</code> keyword followed by the function name, a list of parameters (enclosed in parentheses), and a block of code (enclosed in curly braces). Here's an example:</p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">sayHello</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>)
}
</code></pre>
<p>You can also specify the return type of a function by using the <code>:</code> symbol followed by the type. If a function doesn't return anything, you can use the <code>Unit</code> type, which is equivalent to <code>void</code> in Java. Here's an example of a function that returns a value:</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">(x: <span class="hljs-type">Int</span>, y: <span class="hljs-type">Int</span>)</span></span>: <span class="hljs-built_in">Int</span> {
    <span class="hljs-keyword">return</span> x + y
}
</code></pre>
<p>And here's an example of a function that doesn't return anything:</p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">printSum</span><span class="hljs-params">(x: <span class="hljs-type">Int</span>, y: <span class="hljs-type">Int</span>)</span></span>: <span class="hljs-built_in">Unit</span> {
    println(x + y)
}
</code></pre>
<p><strong>Calling functions</strong></p>
<p>To call a function in Kotlin, you simply use the function name followed by the arguments (enclosed in parentheses). Here's an example:</p>
<pre><code class="lang-kotlin">sayHello(<span class="hljs-string">"Alice"</span>) <span class="hljs-comment">// prints "Hello, Alice!"</span>

<span class="hljs-keyword">val</span> sum = add(<span class="hljs-number">3</span>, <span class="hljs-number">4</span>) <span class="hljs-comment">// sum is 7</span>
printSum(<span class="hljs-number">5</span>, <span class="hljs-number">6</span>) <span class="hljs-comment">// prints 11</span>
</code></pre>
<p><strong>Default Arguments and Named Arguments</strong></p>
<p>You can also use default and named arguments to make your functions more flexible.</p>
<p><strong>Default arguments</strong> allow you to specify default values for parameters, which means you don't have to specify those values when calling the function.</p>
<p><strong>Named arguments</strong> allow you to specify the parameter names when calling the function, which can make it easier to understand the code.</p>
<p>Here's an example of using default and named arguments:</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">(greeting: <span class="hljs-type">String</span> = <span class="hljs-string">"Hello"</span>, name: <span class="hljs-type">String</span>)</span></span> {
    println(<span class="hljs-string">"<span class="hljs-variable">$greeting</span>, <span class="hljs-variable">$name</span>!"</span>)
}

greet(<span class="hljs-string">"Hi"</span>, <span class="hljs-string">"Bob"</span>) <span class="hljs-comment">// prints "Hi, Bob!"</span>
greet(name = <span class="hljs-string">"Alice"</span>) <span class="hljs-comment">// prints "Hello, Alice!"</span>
</code></pre>
<p>That's a brief overview of how to define and call functions in Kotlin. In the next section, we'll look at how to define and use classes and objects in Kotlin.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Congratulations – you now have a solid foundation in the basics of Kotlin syntax! You've learned how to declare variables, use control flow statements, and define and call functions.</p>
<p>In the <a target="_blank" href="https://hardiksachan.hashnode.dev/the-essential-guide-to-object-oriented-programming-in-kotlin">next article</a>, we'll dive deeper into Kotlin by exploring classes and objects. You'll learn how to define your own classes, create objects from those classes, and use inheritance and polymorphism to create more complex and powerful code.</p>
<p>So don't stop now – keep learning and practicing, and you'll be on your way to becoming a Kotlin pro in no time!</p>
]]></content:encoded></item><item><title><![CDATA[Build a Light/Dark Theme Toggle with Jetpack Compose in Android: A Step-by-Step Guide]]></title><description><![CDATA[One of the features that can elevate your app is the ability to switch between light and dark themes from within the app. In this tutorial, we'll show you how to create a theme toggle in Android using Jetpack Compose.
First, let's start by setting up...]]></description><link>https://hardiksachan.com/build-a-lightdark-theme-toggle-with-jetpack-compose-in-android-a-step-by-step-guide</link><guid isPermaLink="true">https://hardiksachan.com/build-a-lightdark-theme-toggle-with-jetpack-compose-in-android-a-step-by-step-guide</guid><category><![CDATA[Android]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[Jetpack Compose]]></category><category><![CDATA[android app development]]></category><category><![CDATA[theme]]></category><dc:creator><![CDATA[Hardik Sachan]]></dc:creator><pubDate>Fri, 30 Dec 2022 06:00:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1672466364871/b5cecd83-387f-4fe0-a11e-09aa478472a5.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>One of the features that can elevate your app is the ability to switch between light and dark themes from within the app. In this tutorial, we'll show you how to create a theme toggle in Android using Jetpack Compose.</p>
<p>First, let's start by setting up our project for Jetpack Compose. If you're new to Jetpack Compose, you can check out the official documentation for more information on getting started.</p>
<p>Next, let's create a <code>Theme.kt</code> file to hold our theme state. This file will be responsible for storing the current theme and providing a method for toggling between the light and dark themes.</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">ThemeState</span></span>(<span class="hljs-keyword">var</span> theme: Theme) {
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">toggleTheme</span><span class="hljs-params">()</span></span> {
        theme = <span class="hljs-keyword">if</span> (theme == Theme.Light) Theme.Dark <span class="hljs-keyword">else</span> Theme.Light
    }
}

<span class="hljs-keyword">enum</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Theme</span> </span>{
    Light, Dark
}
</code></pre>
<p>Now that we have our theme state set up, let's create a button that will allow us to toggle between the light and dark themes. We'll use the <code>@Composable</code> annotation to define a function that will be responsible for rendering the button.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">ToggleThemeButton</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">val</span> themeState = remember { ThemeState(Theme.Light) }
    Button(onClick = { themeState.toggleTheme() }) {
        Text(<span class="hljs-string">"Toggle Theme"</span>)
    }
}
</code></pre>
<p>Finally, we'll need to apply the current theme to our app. We can do this by wrapping our app's content in a <code>MaterialTheme</code> component and setting the <code>theme</code> attribute based on the current value of our <code>ThemeState</code>.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">App</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">val</span> themeState = remember { ThemeState(Theme.Light) }
    MaterialTheme(
        theme = <span class="hljs-keyword">if</span> (themeState.theme == Theme.Light) lightTheme <span class="hljs-keyword">else</span> darkTheme
    ) {
        <span class="hljs-comment">// app content goes here</span>
    }
}
</code></pre>
<p>That's it! With these steps, you should now have a working light/dark theme toggle in your Android app using Jetpack Compose. You can customize the theme and the toggle button to fit the needs of your app.</p>
<hr />
<p>I hope this article helps you build a light/dark theme toggle with Jetpack Compose in Android. Let me know if you have any questions or need further clarification on any of the steps.</p>
]]></content:encoded></item><item><title><![CDATA[Exploring Kotlin's Sealed Classes for Improved Type Safety in Android]]></title><description><![CDATA[Introduction
Are you tired of dealing with pesky type errors in your Android app? Fear not, Kotlin's sealed classes are here to save the day! Sealed classes are a special type of class that can only have a limited number of subclasses, or sealed subc...]]></description><link>https://hardiksachan.com/exploring-kotlins-sealed-classes-for-improved-type-safety-in-android</link><guid isPermaLink="true">https://hardiksachan.com/exploring-kotlins-sealed-classes-for-improved-type-safety-in-android</guid><category><![CDATA[Android]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[Types]]></category><category><![CDATA[Android Studio]]></category><category><![CDATA[app development]]></category><dc:creator><![CDATA[Hardik Sachan]]></dc:creator><pubDate>Thu, 29 Dec 2022 05:53:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1672293157627/96722084-bcc4-4b1c-814d-65a842ae67a4.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Are you tired of dealing with pesky type errors in your Android app? Fear not, Kotlin's sealed classes are here to save the day! Sealed classes are a special type of class that can only have a limited number of subclasses, or sealed subclasses. This feature helps to prevent unexpected or invalid types from sneaking into your code and causing problems.</p>
<p>In this article, we'll dive into the world of sealed classes and how they can be used to improve type safety in your Android app. We'll cover the basics of creating and implementing sealed classes, as well as the benefits of using them. We'll also provide some examples of sealed classes in action and offer tips for using them effectively in your Android projects. So buckle up and get ready to say goodbye to those pesky type errors!</p>
<h2 id="heading-what-are-sealed-classes-in-kotlin">What are Sealed Classes in Kotlin?</h2>
<p>Sealed classes in Kotlin are a bit like the popular children's game "20 Questions." Just like in the game, sealed classes allow you to create a limited set of options (or subclasses) and then narrow down the possibilities until you find the correct answer (or subclass).</p>
<p>To create a sealed class in Kotlin, you simply use the <code>sealed</code> keyword followed by the class definition. For example:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">sealed</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Shape</span> </span>{
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Circle</span></span>(<span class="hljs-keyword">val</span> radius: <span class="hljs-built_in">Double</span>): Shape()
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Rectangle</span></span>(<span class="hljs-keyword">val</span> width: <span class="hljs-built_in">Double</span>, <span class="hljs-keyword">val</span> height: <span class="hljs-built_in">Double</span>): Shape()
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Triangle</span></span>(<span class="hljs-keyword">val</span> base: <span class="hljs-built_in">Double</span>, <span class="hljs-keyword">val</span> height: <span class="hljs-built_in">Double</span>): Shape()
}
</code></pre>
<p>In this example, the <code>Shape</code> class is the sealed class and <code>Circle</code>, <code>Rectangle</code>, and <code>Triangle</code> are its sealed subclasses. Notice that each sealed subclass must be defined inside the body of the sealed class and must also extend the sealed class.</p>
<p>Unlike traditional inheritance hierarchies, a sealed class can only have a fixed number of subclasses, which must be explicitly listed in the sealed class definition. This helps to ensure that all possible cases are covered and prevents the possibility of unexpected or invalid subclasses.</p>
<p>Using sealed classes in Android can help to improve code readability and organization, as well as simplify null handling and error checking. We'll delve into these benefits in more detail later on in the article. So, the next time you're trying to figure out the shape of an object in your Android app, just think of sealed classes as your very own "20 Questions" game!</p>
<h2 id="heading-benefits-of-using-sealed-classes-in-android">Benefits of Using Sealed Classes in Android</h2>
<p>Sealed classes in Kotlin are a real treat for Android developers. Not only do they help to improve type safety in your code, but they also make it easier to keep your code clean, organized, and bug-free. Here are just a few of the benefits of using sealed classes in Android:</p>
<ul>
<li><p><strong>Improved type safety:</strong> With sealed classes, you can be sure that your code is handling all possible cases and won't break when an unexpected or invalid type is encountered. This can save you a lot of headaches and debugging time in the long run.</p>
</li>
<li><p><strong>Enhanced code readability and organization:</strong> Sealed classes allow you to group related types together and clearly define their relationships. This makes your code easier to understand and navigate, especially for other developers working on the same codebase.</p>
</li>
<li><p><strong>Simplified null handling and error checking:</strong> Sealed classes can help to reduce the risk of null reference errors by ensuring that all possible cases are covered. This can make your code more robust and reliable, especially in situations where null values are expected or allowed.</p>
</li>
</ul>
<p>So the next time you're feeling overwhelmed by the chaos of Android development, just remember that sealed classes are here to help! With their powerful type-safety features and code organization benefits, sealed classes are the ultimate code superheroes. Go forth and conquer those bugs and null references with the power of Kotlin's sealed classes!</p>
<h2 id="heading-how-to-use-sealed-classes-in-android">How to Use Sealed Classes in Android</h2>
<p>Ready to unleash the full power of sealed classes in your Android app? Here's how to get started:</p>
<h3 id="heading-creating-a-sealed-class-and-its-subclasses">Creating a sealed class and its subclasses</h3>
<p>To create a sealed class in Kotlin, use the <code>sealed</code> keyword followed by the class definition. Inside the body of the sealed class, define its sealed subclasses by extending the sealed class. Here's an example of a sealed class with three sealed subclasses:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">sealed</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PaymentMethod</span> </span>{
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CreditCard</span></span>(<span class="hljs-keyword">val</span> cardNumber: String, <span class="hljs-keyword">val</span> expirationDate: String, <span class="hljs-keyword">val</span> cvv: String): PaymentMethod()
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DebitCard</span></span>(<span class="hljs-keyword">val</span> cardNumber: String, <span class="hljs-keyword">val</span> expirationDate: String, <span class="hljs-keyword">val</span> cvv: String): PaymentMethod()
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Paypal</span></span>(<span class="hljs-keyword">val</span> email: String): PaymentMethod()
}
</code></pre>
<h3 id="heading-implementing-sealed-classes-in-functions-and-when-expressions">Implementing sealed classes in functions and when expressions</h3>
<p>Once you've created a sealed class and its subclasses, you can use them in your code by matching on the sealed subclasses with a <code>when</code> expression. For example, you might use a sealed class to represent different payment methods in an e-commerce app, like this:</p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">processPayment</span><span class="hljs-params">(paymentMethod: <span class="hljs-type">PaymentMethod</span>, amount: <span class="hljs-type">Double</span>)</span></span> {
    <span class="hljs-keyword">when</span> (paymentMethod) {
        <span class="hljs-keyword">is</span> PaymentMethod.CreditCard -&gt; println(<span class="hljs-string">"Charging $<span class="hljs-subst">${amount}</span> to credit card <span class="hljs-subst">${paymentMethod.cardNumber}</span>."</span>)
        <span class="hljs-keyword">is</span> PaymentMethod.DebitCard -&gt; println(<span class="hljs-string">"Charging $<span class="hljs-subst">${amount}</span> to debit card <span class="hljs-subst">${paymentMethod.cardNumber}</span>."</span>)
        <span class="hljs-keyword">is</span> PaymentMethod.Paypal -&gt; println(<span class="hljs-string">"Charging $<span class="hljs-subst">${amount}</span> to Paypal account <span class="hljs-subst">${paymentMethod.email}</span>."</span>)
    }
}
</code></pre>
<p>In this function, the <code>when</code> expression is used to match on the different sealed subclasses of <code>PaymentMethod</code>. Based on the subclass that is passed to the function, a different message is printed out indicating the payment method being used.</p>
<h2 id="heading-tips-and-best-practices-for-working-with-sealed-classes">Tips and best practices for working with sealed classes</h2>
<p>Here are a few tips and best practices for working with sealed classes in Android:</p>
<ul>
<li><p>Make sure to list all possible sealed subclasses in the sealed class definition. This will help to ensure that all cases are covered and prevent the possibility of unexpected or invalid subclasses.</p>
</li>
<li><p>Use descriptive names for your sealed subclasses to make your code more readable and easier to understand.</p>
</li>
<li><p>Consider using sealed classes to represent mutually exclusive types in your code. For example, you might use a sealed class to represent different states in a state machine or different error conditions in an error-handling system.</p>
</li>
<li><p>Remember that sealed classes are a great way to improve code readability and organization, as well as reduce the risk of null reference errors and other types of bugs. So don't be afraid to use them liberally in your Android projects!</p>
</li>
</ul>
<p>With these tips and best practices in mind, you'll be well on your way to mastering the art of sealed classes in Android.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In conclusion, sealed classes in Kotlin are like a trusty shield for your Android code. They protect you from all the pesky type errors and null reference demons that haunt your codebase, keeping your app running smoothly and your sanity intact.</p>
<p>Using sealed classes is super easy and can make a huge difference in the organization and reliability of your code. They're particularly handy when you need to handle a bunch of different cases, like filtering a list of articles by category or processing a payment with a specific payment method.</p>
<p>So don't be afraid to wield the power of sealed classes in your Android development journey. With their type-safety superpowers and code organization skills, sealed classes are the ultimate code heroes. Go forth and conquer those bugs and null references with the power of Kotlin's sealed classes!</p>
<p>Happy coding!</p>
]]></content:encoded></item><item><title><![CDATA[Become a Refactoring Pro with These Essential Techniques in Android Studio]]></title><description><![CDATA[Refactoring is the process of improving the design of existing code without changing its functionality. It is an important aspect of software development, as it helps to make code more readable, maintainable, and scalable. In this article, we will le...]]></description><link>https://hardiksachan.com/become-a-refactoring-pro-with-these-essential-techniques-in-android-studio</link><guid isPermaLink="true">https://hardiksachan.com/become-a-refactoring-pro-with-these-essential-techniques-in-android-studio</guid><category><![CDATA[Android]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[Android Studio]]></category><category><![CDATA[android development]]></category><category><![CDATA[intellij]]></category><dc:creator><![CDATA[Hardik Sachan]]></dc:creator><pubDate>Wed, 28 Dec 2022 13:08:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/812003dc2aef3c47754129ff9d9805bd.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Refactoring is the process of improving the design of existing code without changing its functionality. It is an important aspect of software development, as it helps to make code more readable, maintainable, and scalable. In this article, we will learn how to use the refactoring features of Android Studio to improve the quality of our code.</p>
<h2 id="heading-why-refactor"><strong>Why Refactor?</strong></h2>
<p>There are several reasons why you might want to refactor your code:</p>
<ol>
<li><p><strong>Improve readability</strong>: Refactoring can make your code more readable by applying consistent naming conventions, breaking up long methods into smaller ones, and organizing code into logical units.</p>
</li>
<li><p><strong>Reduce complexity</strong>: Refactoring can help to reduce the complexity of your code by identifying and removing unnecessary elements, such as redundant code or dead code.</p>
</li>
<li><p><strong>Improve maintainability</strong>: Refactoring can make it easier to maintain and update your code by improving its structure and organization.</p>
</li>
<li><p><strong>Improve performance</strong>: Refactoring can also improve the performance of your code by identifying and optimizing bottlenecks or inefficiencies.</p>
</li>
</ol>
<h2 id="heading-tldr">TLDR</h2>
<ol>
<li><p><strong>Rename</strong> - <em>Shift + F6</em></p>
</li>
<li><p><strong>Extract Method</strong> - <em>Ctrl + Alt + M</em></p>
</li>
<li><p><strong>Extract Variable</strong> - <em>Ctrl + Alt + V</em></p>
</li>
<li><p><strong>Extract Constant</strong> - <em>Ctrl + Alt + C</em></p>
</li>
<li><p><strong>Inline</strong> - <em>Ctrl + Alt + N</em></p>
</li>
<li><p><strong>Change Signature</strong> - <em>Ctrl + F6</em></p>
</li>
<li><p><strong>Extract Interface</strong> - <em>Ctrl + Alt + B</em></p>
</li>
</ol>
<h2 id="heading-refactoring-tools-in-android-studio"><strong>Refactoring Tools in Android Studio</strong></h2>
<p>Android Studio provides several built-in tools to help you refactor your code. These tools can be accessed through the <strong>Refactor</strong> menu or by using keyboard shortcuts.</p>
<h3 id="heading-rename"><strong>Rename</strong></h3>
<p>The <strong>Rename</strong> refactoring tool allows you to change the name of a symbol (e.g., a class, method, or variable) throughout your code. To use it, simply right-click on the symbol and select <strong>Refactor &gt; Rename</strong>. Alternatively, you can use the keyboard shortcut <strong>Shift + F6</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672232121315/c32e8d26-0c53-468f-b779-cdd78c7d67ef.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-extract-method"><strong>Extract Method</strong></h3>
<p>The <strong>Extract Method</strong> refactoring tool allows you to extract a block of code into a separate method. This can help to reduce the complexity of your code by breaking up long methods into smaller, more manageable chunks. To use it, select the code you want to extract, then right-click and select <strong>Refactor &gt; Extract &gt; Method</strong>. Alternatively, you can use the keyboard shortcut <strong>Ctrl + Alt + M.</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672232200782/2c217d72-6e6e-4d26-a20c-6b59dfd84d68.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-extract-variable"><strong>Extract Variable</strong></h3>
<p>The <strong>Extract Variable</strong> refactoring tool allows you to extract a value or expression into a separate variable. This can help to improve the readability of your code by giving names to complex expressions or values that are used multiple times. To use it, select the value or expression you want to extract, then right-click and select <strong>Refactor &gt; Extract &gt; Variable</strong>. Alternatively, you can use the keyboard shortcut <strong>Ctrl + Alt + V</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672232289366/ee103281-524b-4c30-8902-10b3642653dd.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-extract-constant"><strong>Extract Constant</strong></h3>
<p>The <strong>Extract Constant</strong> refactoring tool is similar to <strong>Extract Variable</strong>, but it creates a constant instead of a variable. Constants are useful for values that are used frequently and are not expected to change, such as hardcoded strings or magic numbers. To use it, select the value you want to extract, then right-click and select <strong>Refactor &gt; Extract &gt; Constant</strong>. Alternatively, you can use the keyboard shortcut <strong>Ctrl + Alt + C</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672232340984/86e233f9-b6c6-405c-b53f-a5866b1e57b9.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-inline"><strong>Inline</strong></h3>
<p>The <strong>Inline</strong> refactoring tool allows you to replace a method or variable with its body or value, respectively. This can be useful when you have a small or simple method or variable that is not being used elsewhere and is adding unnecessary complexity to your code. To use it, right-click on the method or variable and select <strong>Refactor &gt; Inline</strong>. Alternatively, you can use the keyboard shortcut <strong>Ctrl + Alt + N.</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672232399309/82302288-dcc5-4047-8c70-ab115a0b6659.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-change-signature"><strong>Change Signature</strong></h3>
<p>The <strong>Change Signature</strong> refactoring tool allows you to modify the signature of a method, including its name, return type, and parameters. This can be useful when you want to rename a method or change its parameters to better reflect its functionality. To use it, right-click on the method and select <strong>Refactor &gt; Change Signature</strong>. Alternatively, you can use the keyboard shortcut <strong>Ctrl + F6</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672232507249/a369fc01-88d5-48a9-9c41-a8c6dea0b18e.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-extract-interface"><strong>Extract Interface</strong></h3>
<p>The <strong>Extract Interface</strong> refactoring tool allows you to extract the common characteristics of a group of classes into a separate interface. This can help to improve the design of your code by promoting code reuse and abstraction. To use it, select the classes you want to extract, then right-click and select <strong>Refactor &gt; Extract &gt; Interface</strong>. Alternatively, you can use the keyboard shortcut <strong>Ctrl + Alt + B</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672232546673/cec5d485-035b-4fb3-af8b-d4800d167ca4.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>In this article, we learned about the importance of refactoring in software development and how to use the refactoring tools in Android Studio to improve the quality of our code. By applying these techniques, we can make our code more readable, maintainable, and efficient, which can save time and effort in the long run.</p>
<p>Remember to always test your code thoroughly after refactoring to ensure that the changes you made did not introduce any unintended bugs or side effects.</p>
<p>By regularly incorporating refactoring into your workflow, you can keep your codebase in top shape and make it easier for yourself and others to work with. Happy refactoring!</p>
]]></content:encoded></item><item><title><![CDATA[How to Create a Search View in Jetpack Compose: A Step-by-Step Guide]]></title><description><![CDATA[I recently came across a challenge when I was making an app completely using Jetpack Compose, if you haven't heard about it check it out. I needed a Search View, but there was no out-of-the-box solution for it so I created my own. Here's is how it lo...]]></description><link>https://hardiksachan.com/how-to-create-a-search-view-in-jetpack-compose-a-step-by-step-guide</link><guid isPermaLink="true">https://hardiksachan.com/how-to-create-a-search-view-in-jetpack-compose-a-step-by-step-guide</guid><category><![CDATA[Android]]></category><category><![CDATA[Jetpack Compose]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[android app development]]></category><category><![CDATA[jetpack]]></category><dc:creator><![CDATA[Hardik Sachan]]></dc:creator><pubDate>Tue, 27 Dec 2022 05:12:48 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1633482647499/SeXcKAiyC.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I recently came across a challenge when I was making an app completely using Jetpack Compose, if you haven't heard about it <a target="_blank" href="putlinkhere.com">check it out</a>. I needed a Search View, but there was no out-of-the-box solution for it so I created my own. Here's is how it looked like:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672117816843/20433abb-7255-492a-a0c7-bfe7e3f3937e.gif?width=300" alt class="image--center mx-auto" /></p>
<p>To create a search view in Jetpack Compose, we need to define three functions: <code>ExpandableSearchView</code>, <code>CollapsedSearchView</code>, and <code>ExpandedSearchView</code>. The <code>ExpandableSearchView</code> function will contain the logic for expanding and collapsing the search view, while the <code>CollapsedSearchView</code> and <code>ExpandedSearchView</code> functions will define the appearance and behavior of the search view when it is collapsed and expanded, respectively.</p>
<p>First, let's define the <code>ExpandableSearchView</code> function. It should take the following arguments:</p>
<ul>
<li><p><code>searchDisplay</code>: This is the string that is displayed in the search field when it is collapsed.</p>
</li>
<li><p><code>onSearchDisplayChanged</code>: This is a lambda function that is called when the search display is changed. You can use this function to update the UI or perform a search based on the new search display.</p>
</li>
<li><p><code>onSearchDisplayClosed</code>: This is a lambda function that is called when the search display is closed. You can use this function to reset the search display or clear the search results.</p>
</li>
<li><p><code>modifier</code>: This is an optional argument that allows you to specify a <code>Modifier</code> for the search view.</p>
</li>
<li><p><code>expandedInitially</code>: This is an optional argument that specifies whether the search view should be expanded initially. The default value is <code>false</code>.</p>
</li>
<li><p><code>tint</code>: This is an optional argument that specifies the color of the search icon and the text in the search field. The default value is the <code>onPrimary</code> color from the <code>MaterialTheme</code>.</p>
</li>
</ul>
<p>Here's the code for the <code>ExpandableSearchView</code> function:</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">ExpandableSearchView</span><span class="hljs-params">(
    searchDisplay: <span class="hljs-type">String</span>,
    onSearchDisplayChanged: (<span class="hljs-type">String</span>) -&gt; <span class="hljs-type">Unit</span>,
    onSearchDisplayClosed: () -&gt; <span class="hljs-type">Unit</span>,
    modifier: <span class="hljs-type">Modifier</span> = Modifier,
    expandedInitially: <span class="hljs-type">Boolean</span> = <span class="hljs-literal">false</span>,
    tint: <span class="hljs-type">Color</span> = MaterialTheme.colors.onPrimary
)</span></span> {
    <span class="hljs-keyword">val</span> (expanded, onExpandedChanged) = remember {
        mutableStateOf(expandedInitially)
    }


    Crossfade(targetState = expanded) { isSearchFieldVisible -&gt;
        <span class="hljs-keyword">when</span> (isSearchFieldVisible) {
            <span class="hljs-literal">true</span> -&gt; ExpandedSearchView(
                searchDisplay = searchDisplay,
                onSearchDisplayChanged = onSearchDisplayChanged,
                onSearchDisplayClosed = onSearchDisplayClosed,
                onExpandedChanged = onExpandedChanged,
                modifier = modifier,
                tint = tint
            )

            <span class="hljs-literal">false</span> -&gt; CollapsedSearchView(
                onExpandedChanged = onExpandedChanged,
                modifier = modifier,
                tint = tint
            )
        }
    }
}
</code></pre>
<p>The <code>ExpandableSearchView</code> function uses a <code>Crossfade</code> component to switch between the collapsed and expanded states of the search view. When the search view is collapsed, it displays the <code>CollapsedSearchView</code> component. When the search view is expanded, it displays the <code>ExpandedSearchView</code> component.</p>
<p>Next, we need to define the <code>CollapsedSearchView</code> and <code>ExpandedSearchView</code> components.</p>
<p>The <code>CollapsedSearchView</code> component is a simple row that displays a text label and a search icon button. When the search icon button is clicked, the <code>CollapsedSearchView</code> component calls the <code>onExpandedChanged</code> lambda function to expand the search view.</p>
<p>Here is the code for the <code>CollapsedSearchView</code> component:</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">CollapsedSearchView</span><span class="hljs-params">(
    onExpandedChanged: (<span class="hljs-type">Boolean</span>) -&gt; <span class="hljs-type">Unit</span>,
    modifier: <span class="hljs-type">Modifier</span> = Modifier,
    tint: <span class="hljs-type">Color</span> = MaterialTheme.colors.onPrimary,
)</span></span> {

    Row(
        modifier = modifier
            .fillMaxWidth()
            .padding(vertical = <span class="hljs-number">2</span>.dp),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            text = <span class="hljs-string">"Tasks"</span>,
            style = MaterialTheme.typography.h6,
            modifier = Modifier
                .padding(start = <span class="hljs-number">16</span>.dp)
        )
        IconButton(onClick = { onExpandedChanged(<span class="hljs-literal">true</span>) }) {
            SearchIcon(iconTint = tint)
        }
    }
}
</code></pre>
<p>The <code>ExpandedSearchView</code> component is a row that contains a back icon button and a text field for entering the search query. The text field is bound to the <code>searchDisplay</code> variable, so any changes to the search query will be reflected in the <code>searchDisplay</code> variable and the <code>onSearchDisplayChanged</code> lambda function will be called. When the user clicks the back icon button or hits the "done" button on the keyboard, the <code>ExpandedSearchView</code> component calls the <code>onSearchDisplayClosed</code> lambda function and collapses the search view.</p>
<p>Here is the code for the <code>ExpandedSearchView</code> component:</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">ExpandedSearchView</span><span class="hljs-params">(
    searchDisplay: <span class="hljs-type">String</span>,
    onSearchDisplayChanged: (<span class="hljs-type">String</span>) -&gt; <span class="hljs-type">Unit</span>,
    onSearchDisplayClosed: () -&gt; <span class="hljs-type">Unit</span>,
    onExpandedChanged: (<span class="hljs-type">Boolean</span>) -&gt; <span class="hljs-type">Unit</span>,
    modifier: <span class="hljs-type">Modifier</span> = Modifier,
    tint: <span class="hljs-type">Color</span> = MaterialTheme.colors.onPrimary,
)</span></span> {
    <span class="hljs-keyword">val</span> focusManager = LocalFocusManager.current

    <span class="hljs-keyword">val</span> textFieldFocusRequester = remember { FocusRequester() }

    SideEffect {
        textFieldFocusRequester.requestFocus()
    }

    <span class="hljs-keyword">var</span> textFieldValue <span class="hljs-keyword">by</span> remember {
        mutableStateOf(TextFieldValue(searchDisplay, TextRange(searchDisplay.length)))
    }

    Row(
        modifier = modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.Start,
        verticalAlignment = Alignment.CenterVertically
    ) {
        IconButton(onClick = {
            onExpandedChanged(<span class="hljs-literal">false</span>)
            onSearchDisplayClosed()
        }) {
            Icon(
                painter = painterResource(id = R.drawable.ic_back),
                contentDescription = <span class="hljs-string">"back icon"</span>,
                tint = tint
            )
        }
        TextField(
            value = textFieldValue,
            onValueChange = {
                textFieldValue = it
                onSearchDisplayChanged(it.text)
            },
            trailingIcon = {
                SearchIcon(iconTint = tint)
            },
            modifier = Modifier
                .fillMaxWidth()
                .focusRequester(textFieldFocusRequester),
            label = {
                Text(text = <span class="hljs-string">"Search"</span>, color = tint)
            },
            keyboardOptions = KeyboardOptions(
                imeAction = ImeAction.Done
            ),
            keyboardActions = KeyboardActions(
                onDone = {
                    focusManager.clearFocus()
                }
            )
        )
    }
}
</code></pre>
<p>Finally, we need to define a <code>SearchIcon</code> function that creates an icon for the search view. This function takes a <code>iconTint</code> argument to specify the color of the icon.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">SearchIcon</span><span class="hljs-params">(iconTint: <span class="hljs-type">Color</span>)</span></span> {
    Icon(
        painter = painterResource(id = R.drawable.ic_search),
        contentDescription = <span class="hljs-string">"search icon"</span>,
        tint = iconTint
    )
}
</code></pre>
<p>With these functions defined, we can now use the <code>ExpandableSearchView</code> to create an expandable search view in Jetpack Compose. To do this, simply call the <code>ExpandableSearchView</code> function and pass the necessary arguments.</p>
<p>That's it! You should now have a working expandable search view in Jetpack Compose. You can customize the appearance and behavior of the search view by modifying the <code>ExpandableSearchView</code>, <code>CollapsedSearchView</code>, and <code>ExpandedSearchView</code> functions as needed.</p>
<p>I hope this tutorial has helped you understand how to create an expandable search view in Jetpack Compose. If you have any questions or comments, feel free to leave them below.</p>
]]></content:encoded></item><item><title><![CDATA[Understanding and Using Arrays and ArrayLists in Kotlin: A Comprehensive Guide]]></title><description><![CDATA[Kotlin, a modern programming language developed by JetBrains, is a statically typed language that runs on the Java Virtual Machine. It is concise, expressive, and designed to be more readable and safer than Java. Kotlin is fully interoperable with Ja...]]></description><link>https://hardiksachan.com/understanding-and-using-arrays-and-arraylists-in-kotlin-a-comprehensive-guide</link><guid isPermaLink="true">https://hardiksachan.com/understanding-and-using-arrays-and-arraylists-in-kotlin-a-comprehensive-guide</guid><category><![CDATA[array]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[Android]]></category><category><![CDATA[data structures]]></category><category><![CDATA[ArrayList]]></category><dc:creator><![CDATA[Hardik Sachan]]></dc:creator><pubDate>Sun, 25 Dec 2022 04:43:43 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/4a5816cc7c3df6e3eb1889726e0abc31.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Kotlin, a modern programming language developed by JetBrains, is a statically typed language that runs on the Java Virtual Machine. It is concise, expressive, and designed to be more readable and safer than Java. Kotlin is fully interoperable with Java and can be used to develop Android apps, server-side applications, and much more.</p>
<p>In this article, we will discuss two important data structures in Kotlin: <code>Array</code> and <code>ArrayList</code>. These data structures are used to store and manipulate collections of data in Kotlin.</p>
<h2 id="heading-array"><strong>Array</strong></h2>
<p>An array is a collection of elements that are stored in a contiguous block of memory. All elements in an array must be of the same type. In Kotlin, arrays are represented by the <code>Array</code> class, which has a fixed size and provides indexed access to its elements.</p>
<p>Here is an example of how to create and initialize an array in Kotlin:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> numbers = arrayOf(<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-number">5</span>)
</code></pre>
<p>In this example, we have created an array of integers called <code>numbers</code>. The <code>arrayOf</code> function is used to create an array and initialize it with the given elements.</p>
<p>We can also create an array of a specific size and type using the <code>arrayOfNulls</code> function:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> names = arrayOfNulls&lt;String&gt;(<span class="hljs-number">5</span>)
</code></pre>
<p>This creates an array of strings called <code>names</code> with a size of 5. All elements in the array are initialized to <code>null</code>.</p>
<p>We can access the elements of an array using the index operator (<code>[]</code>):</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> firstNumber = numbers[<span class="hljs-number">0</span>]  <span class="hljs-comment">// firstNumber will be 1</span>
<span class="hljs-keyword">val</span> thirdNumber = numbers[<span class="hljs-number">2</span>]  <span class="hljs-comment">// thirdNumber will be 3</span>
</code></pre>
<p>We can also use the <code>for</code> loop to iterate over the elements of an array:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">for</span> (number <span class="hljs-keyword">in</span> numbers) {
    println(number)
}
</code></pre>
<p>This will print all the elements of the <code>numbers</code> array on separate lines.</p>
<p>One important thing to note about arrays in Kotlin is that they are mutable, meaning that we can change the elements of the array after it has been created. Here is an example of how to change the elements of an array:</p>
<pre><code class="lang-kotlin">numbers[<span class="hljs-number">0</span>] = <span class="hljs-number">10</span>  <span class="hljs-comment">// the first element of the array is now 10</span>
</code></pre>
<h2 id="heading-arraylist"><strong>ArrayList</strong></h2>
<p>An <code>ArrayList</code> is a resizable array implementation of the <code>List</code> interface. It is similar to an array, but it can grow or shrink as needed to accommodate the elements being added or removed. In Kotlin, <code>ArrayList</code> is represented by the <code>ArrayList</code> class.</p>
<p>Here is an example of how to create and initialize an <code>ArrayList</code> in Kotlin:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> numbers = arrayListOf(<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-number">5</span>)
</code></pre>
<p>In this example, we have created an <code>ArrayList</code> of integers called <code>numbers</code>. The <code>arrayListOf</code> function is used to create an <code>ArrayList</code> and initialize it with the given elements.</p>
<p>We can also create an empty <code>ArrayList</code> and add elements to it later:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> names = ArrayList&lt;String&gt;()
names.add(<span class="hljs-string">"Alice"</span>)
names.add(<span class="hljs-string">"Bob"</span>)
names.add(<span class="hljs-string">"Charlie"</span>)
</code></pre>
<p>We can access the elements of an <code>ArrayList</code> using the index operator (<code>[]</code>) or the <code>get</code> function:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> firstName = names[<span class="hljs-number">0</span>]  <span class="hljs-comment">// firstName will be "Alice"</span>
<span class="hljs-keyword">val</span> thirdName = names.<span class="hljs-keyword">get</span>(<span class="hljs-number">2</span>)  <span class="hljs-comment">// thirdName will be "Charlie"</span>
</code></pre>
<p>We can also use the <code>for</code> loop to iterate over the elements of an <code>ArrayList</code>:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">for</span> (name <span class="hljs-keyword">in</span> names) {
    println(name)
}
</code></pre>
<p>This will print all the elements of the <code>names</code> <code>ArrayList</code> on separate lines.</p>
<p>We can add or remove elements from an <code>ArrayList</code> using the <code>add</code> and <code>remove</code> functions:</p>
<pre><code class="lang-kotlin">names.add(<span class="hljs-string">"David"</span>)  <span class="hljs-comment">// the names ArrayList now contains ["Alice", "Bob", "Charlie", "David"]</span>
names.remove(<span class="hljs-string">"Bob"</span>)  <span class="hljs-comment">// the names ArrayList now contains ["Alice", "Charlie", "David"]</span>
</code></pre>
<p>We can also use the <code>clear</code> function to remove all elements from an <code>ArrayList</code>:</p>
<pre><code class="lang-kotlin">names.clear()  <span class="hljs-comment">// the names ArrayList is now empty</span>
</code></pre>
<p>One important thing to note about <code>ArrayList</code> is that it is mutable, meaning that we can change the elements of the <code>ArrayList</code> after it has been created.</p>
<p>In summary, <code>Array</code> and <code>ArrayList</code> are important data structures in Kotlin that are used to store and manipulate collections of data. While both are similar in many ways, <code>ArrayList</code> is more flexible and can grow or shrink as needed, while <code>Array</code> has a fixed size. Both are mutable, which means that we can change the elements of the collection after it has been created.</p>
]]></content:encoded></item><item><title><![CDATA[Getting Started with Linux Terminal]]></title><description><![CDATA[Hello there, In this article, we'll take a look at some of the basic commands used in Linux-based systems.
Anatomy of a basic Linux prompt


In lines 1 and 2, we see hardik@nitro5-fedora. Here hardik is the username of the logged-in user and nitro5-f...]]></description><link>https://hardiksachan.com/getting-started-with-linux-terminal</link><guid isPermaLink="true">https://hardiksachan.com/getting-started-with-linux-terminal</guid><category><![CDATA[Bash]]></category><category><![CDATA[linux for beginners]]></category><category><![CDATA[linux-basics]]></category><dc:creator><![CDATA[Hardik Sachan]]></dc:creator><pubDate>Tue, 28 Dec 2021 11:05:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/4Mw7nkQDByk/upload/v1640688166109/u7T5IEeXMR.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello there, In this article, we'll take a look at some of the basic commands used in Linux-based systems.</p>
<h1 id="heading-anatomy-of-a-basic-linux-prompt">Anatomy of a basic Linux prompt</h1>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640688728815/HSb8u-_i8.png" alt="image.png" /></p>
<ul>
<li>In lines 1 and 2, we see <code>hardik@nitro5-fedora</code>. Here <code>hardik</code> is the username of the logged-in user and <code>nitro5-fedora</code> is the name of the pc.</li>
<li>In line 1, <code>~</code> indicates that we are in the <strong>home</strong> directory.</li>
<li>In line 2, <code>/</code> indicates that we are at the <strong>root</strong> of the filesystem.</li>
<li>The <code>$</code> symbol indicates that you are interacting with the system as a regular user. If you have <strong>sudo</strong> privileges, the <code>$</code> turns into a <code>#</code>.</li>
</ul>
<blockquote>
<p>NOTE: From here on now, I’ll be using <em>zsh</em> instead of <em>bash</em>. But don't go away just yet. The commands discussed here work just the same on <em>bash</em> as well. :P</p>
</blockquote>
<h1 id="heading-some-basic-linux-commands">Some basic Linux commands</h1>
<h2 id="heading-date">date</h2>
<p><code>date</code> command is used to show the current system date and time.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640688744164/8vc1vmgML.png" alt="image.png" /></p>
<h2 id="heading-ls">ls</h2>
<p><code>ls</code> command lists the files present in the current directory.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640688766537/tEz6S5r2m.png" alt="image.png" /></p>
<p>Let’s take a look at some important flags for <code>ls</code> command</p>
<ul>
<li><p><code>-R</code></p>
<p>  This flag lists the files recursively i.e. it will also list the file present in subdirectories and their subdirectories and so on</p>
<p>  Here’s a sample</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640688784750/zxuUoFZA-.png" alt="image.png" /></p>
</li>
<li><p><code>-l</code></p>
<p>  This flag shows some additional information about the files like <em>permission string</em>, <em>owner</em>, <em>group</em> of the <em>owner</em>, file size in bytes</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640688803346/Ka5fdo5Xr.png" alt="image.png" /></p>
</li>
<li><p><code>-a</code></p>
<p>  This flag lists <em>hidden</em> files as well</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640688834968/5bw_J_ixd.png" alt="image.png" /></p>
</li>
</ul>
<h2 id="heading-cat">cat</h2>
<p><code>cat</code> command is used to display, copy, combine and create new files.</p>
<ul>
<li><p>Creating new files</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640688848461/fZ7Sc64fA.png" alt="image.png" /></p>
</li>
<li><p>Viewing a file</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640688868555/aWf73l4xu.png" alt="image.png" /></p>
</li>
<li><p>Combining two files</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640688889067/lS54TJySR.png" alt="image.png" /></p>
</li>
</ul>
<h2 id="heading-pwd">pwd</h2>
<p><code>pwd</code> stands for <em>print working directory</em> and does the same.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640688902550/1UwVAbEv3.png" alt="image.png" /></p>
<h2 id="heading-rm">rm</h2>
<p><code>rm</code> is used to delete files. <code>rmdir</code> can be used to delete directories.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640688916196/1z3USb-Ap.png" alt="image.png" /></p>
<p>You can use <code>-rf</code> flag to delete a directory recursively.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640688929279/1LJ69HEtB.png" alt="image.png" /></p>
<h2 id="heading-cd">cd</h2>
<p><code>cd</code> stands for <em>change directory</em> and is used to do the same.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640688941707/IXXiU9R2C.png" alt="image.png" /></p>
<blockquote>
<p>Please ignore the <em>warnings.</em> They are related to my prompt configuration.</p>
</blockquote>
<p><strong>Some important <code>cd</code> commands</strong></p>
<ul>
<li><code>cd ..</code> is used to navigate to one level up in file system.</li>
<li><code>cd ~</code> navigates you to your <strong>home</strong> folder.</li>
</ul>
<h2 id="heading-mkdir">mkdir</h2>
<p><code>mkdir</code> is used to create a new directory.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640688977752/6M_RIGbIB.png" alt="image.png" /></p>
<h2 id="heading-mv">mv</h2>
<p><code>mv</code> stands for <em>move</em>. It is used to move files around the file system. It can also be used to rename files</p>
<p><strong>SYNTAX</strong></p>
<p><code>mv [OPTIONS] source destination</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640688988564/dsz--aZh_.png" alt="image.png" /></p>
<h2 id="heading-cp">cp</h2>
<p><code>cp</code> stands for <em>copy</em> and is used to copy files and folders</p>
<p><strong>SYNTAX</strong></p>
<p><code>cp [OPTIONS] source destination</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640689000187/lZpZL625V.png" alt="image.png" /></p>
<h2 id="heading-man">man</h2>
<p><code>man</code> command is used to access documentation of the commands that are available in the os. Here is a sample</p>
<pre><code class="lang-bash">man curl
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640689012710/M08OuSvsP.png" alt="image.png" /></p>
<p>To exit this page, press <code>q</code></p>
<h2 id="heading-history">history</h2>
<p><code>history</code> command shows the commands used in this terminal session.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640689032629/HA2BBAuem.png" alt="image.png" /></p>
<h2 id="heading-clear">clear</h2>
<p><code>clear</code> command clears the terminal. In modern <em>terminal emulators</em>, you can press <code>Ctrl + L</code> to do the same.</p>
<hr />
<p>Hope you liked this short article. See you next time. :D</p>
]]></content:encoded></item><item><title><![CDATA[Introduction to Appwrite Cloud Functions with Android and Kotlin]]></title><description><![CDATA[In this article, we'll take a look at Cloud Functions in appwrite.io and how to use them with Kotlin or Android.
Here's an overview of what we'll be doing. 

We'll create a classic "Hello, World!" program with functions
We'll write a function to get ...]]></description><link>https://hardiksachan.com/introduction-to-appwrite-cloud-functions-with-android-and-kotlin</link><guid isPermaLink="true">https://hardiksachan.com/introduction-to-appwrite-cloud-functions-with-android-and-kotlin</guid><category><![CDATA[Android]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[Open Source]]></category><category><![CDATA[#hacktoberfest ]]></category><category><![CDATA[2Articles1Week]]></category><dc:creator><![CDATA[Hardik Sachan]]></dc:creator><pubDate>Thu, 21 Oct 2021 14:41:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1634725189121/MoRVURvd5.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article, we'll take a look at <a target="_blank" href="https://appwrite.io/docs/functions">Cloud Functions in appwrite.io</a> and how to use them with Kotlin or Android.</p>
<p>Here's an overview of what we'll be doing. </p>
<ul>
<li>We'll create a classic "Hello, World!" program with functions</li>
<li>We'll write a function to get Covid-19 stats from <a target="_blank" href="https://covid19api.com/">Covid19Api</a></li>
<li>We'll build an android app around the above function</li>
</ul>
<p>Before we start, if you like to dive directly into the code, here's the <a target="_blank" href="https://github.com/hardiksachan/introduction-to-appwrite-functions">github repo</a></p>
<h1 id="creating-a-new-appwrite-project">Creating a new Appwrite project</h1>
<p>Before we dive into creating functions, let's set up a new Appwrite project to which we will add our functions. If you already have an appwrite project you can skip this section.</p>
<p>To get Appwrite up and running, follow <a target="_blank" href="https://appwrite.io/docs/installation">these instructions</a> and create a new account.</p>
<p>Next, follow the onscreen instructions to create a new project - 
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634754810423/fzuntU29V.png" alt="New project name" /></p>
<h1 id="hello-world-with-appwrite-functions">Hello World with Appwrite Functions</h1>
<p>This is a pretty basic project to implement but it will make us familiar with the process of creating a new Appwrite Function. Let's get started  -</p>
<p>First of all, we need a new Kotlin project, I'm going to use <a target="_blank" href="https://www.jetbrains.com/idea/">Intellij Idea</a> as an IDE with <a target="_blank" href="https://gradle.org/">gradle build system</a>.</p>
<p>Here's the configuration I'm using to create a new project - 
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634751219898/R50XksTOl.png" alt="New project config" /></p>
<p>Next, let's create a new file named <code>Main.kt</code> in <code>hello-world/src/main/kotlin</code> and put the following code in it - </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">"Hello, world!"</span>)
}
</code></pre>
<p>...and we are done! </p>
<h4 id="now-lets-add-this-to-an-appwrite-function">Now let's add this to an Appwrite function.</h4>
<p>Appwrite requires us to create a "fat jar" which is just a fancy way of saying that we need to include all runtime dependencies in our jar file. To achieve this we have to add the following lines to <code>build.gradle.kts</code> - </p>
<pre><code class="lang-kotlin">tasks.withType&lt;Jar&gt;() {
    manifest {
        attributes[<span class="hljs-string">"Main-Class"</span>] = <span class="hljs-string">"MainKt"</span>
    }

    from(sourceSets.main.<span class="hljs-keyword">get</span>().output)

    dependsOn(configurations.runtimeClasspath)
    from({
        configurations.runtimeClasspath.<span class="hljs-keyword">get</span>()
            .filter { it.name.endsWith(<span class="hljs-string">"jar"</span>) }
            .map { zipTree(it) }
    })
}
</code></pre>
<p>These lines basically instruct Gradle to build a "fat jar". Now to actually build a jar, we need to run the following task -</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634752559348/wGvz-w9Cq.png" alt="Build jar task" /></p>
<p>This will create the required jar file in <code>hello-world/build/libs/hello-world-1.0-SNAPSHOT.jar</code></p>
<p>Now, to upload this to Appwrite we need to package this in a <code>tar</code> file. To do this run the following command inside the <code>libs</code> directory - </p>
<pre><code class="lang-bash">tar -zcvf code.tar.gz .\hello-world-1.0-SNAPSHOT.jar
</code></pre>
<p>This will create a file named <code>code.tar.gz</code> in the <code>libs</code> directory. We will need this file later.</p>
<h3 id="creating-a-new-appwrite-function">Creating a new Appwrite Function</h3>
<p>Now, let's create a new appwrite function from the appwrite console. Navigate to <code>Functions</code> tab on Left pane, and click on <code>Add Function</code> button. Give it a name, in this case I'm using <code>hello-world</code>, and for the runtime, choose <code>Java 16.0</code></p>
<p>Next, let's create a new deploy tag - </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634755606240/kwYycTjkU.png" alt="Hello World Deploy tag" /></p>
<p>Here's the Command - </p>
<pre><code class="lang-bash">java -jar hello-world-1.0-SNAPSHOT.jar
</code></pre>
<p>Here we upload the tar file we created earlier. Click <code>Activate</code> and voila, we're done. :D</p>
<p>Let's test out the function. Click on <code>Execute Now</code> we don't need to pass any data to this function. Navigate to logs and check the <code>output</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634755836224/6yPnIcio4.png" alt="Hello World successful execution" /></p>
<p>And you just created your first appwrite function. Cheers 🍻</p>
<h3 id="a-little-upgrade">A little upgrade</h3>
<p>Now let's make this function a little more useful. Instead of printing <code>Hello, world!</code> all the time, we'll pass a name to this function.</p>
<h4 id="a-note-on-appwritefunctiondata-and-appwritefunctioneventdata">A note on <code>APPWRITE_FUNCTION_DATA</code> and <code>APPWRITE_FUNCTION_EVENT_DATA</code></h4>
<p>As mentioned in the <a target="_blank" href="https://appwrite.io/docs/functions">documentation</a>, these <em>environment variables</em> contains the information pertinent to execution of a custom appwrite function.</p>
<p>We use <code>APPWRITE_FUNCTION_DATA</code> when we trigger the function through Appwrite console or via <a target="_blank" href="https://appwrite.io/docs/client/functions?sdk=web#functionsCreateExecution">SDK or HTTP API</a>. <em>This variable contains the data passed in those executions.</em></p>
<p><code>APPWRITE_FUNCTION_EVENT_DATA</code> is used when the function is triggered by some <strong>event</strong> like inserting a new document. <em>This variable contains information regarding that event.</em></p>
<h4 id="lets-get-back-to-the-upgrade">Let's get back to the upgrade</h4>
<p>Now we need to read the name from the <code>APPWRITE_FUNCTION_DATA</code> variable, to do this we add a new function - </p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getNameFromEnv</span><span class="hljs-params">()</span></span>: String =
    System.getenv(<span class="hljs-string">"APPWRITE_FUNCTION_DATA"</span>)
</code></pre>
<p>and update the <code>println</code> statement as follows - </p>
<pre><code class="lang-kotlin">println(<span class="hljs-string">"Hello, <span class="hljs-subst">${getNameFromEnv()}</span>!"</span>)
</code></pre>
<p>Let's build the jar and add a new deploy tag to our appwrite console. You can follow the same instructions from above. And then execute the function passing you name as input.</p>
<p>Let's test it out. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634757891686/uIfRnmh8B.png" alt="Hello Hardik Input" />
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634757847134/45cZRlwGl.png" alt="Hello Hardik output" /></p>
<p>Yay! We're done. 🚀</p>
<h1 id="display-covid-19-stats">Display Covid-19 stats</h1>
<p>By creating the previous project, we got familiar with the process of creating a new Appwrite function with Kotlin. Now, let's build another project which is a little more complex. In this project, we'll see how we can integrate an Appwrite Function with a third-party API. Let's get started.</p>
<p>We will be using <a target="_blank" href="https://covid19api.com/">Covid19Api</a> to get the data.</p>
<p>Before we dive into implementing the function, let's take a quick look at the requirements of what we'll be building - </p>
<ul>
<li>First, we need to read the country from <code>APPWRITE_FUNCTION_DATA</code>.</li>
<li>Now, we need to check if the country is valid.</li>
<li>If the country is valid, we return the stats for that country.</li>
<li>If the country is not valid, we return global stats, with a message indicating the country was not valid.</li>
</ul>
<p>Let's first create a new project. I'll name it <code>get-covid-stats</code>. Then we need a <code>Main.kt</code> file in <code>get-covid-stats/src/main/kotlin</code>. </p>
<p>Now we need to read the country name from <code>APPWRITE_FUNCTION_DATA</code>. Let's do that - </p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">readCountryFromEnv</span><span class="hljs-params">()</span></span>: String = 
    System.getenv(<span class="hljs-string">"APPWRITE_FUNCTION_DATA"</span>)
</code></pre>
<p>and in <code>main</code> let's call it - </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-title">main</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">val</span> country = readCountryFromEnv()
}
</code></pre>
<p>Next, we need to install some dependencies. We need to make Network Requests for that, I'm going to use <a target="_blank" href="https://ktor.io/docs/client.html">Ktor HTTP Client</a> and to parse json let's use <a target="_blank" href="https://github.com/Kotlin/kotlinx.serialization"><code>kotlinx.serialization</code></a>. If you don't know these libraries, don't worry, I'll explain how they work. To install these dependencies add the following lines to <code>build.gradle.kts</code> - </p>
<pre><code class="lang-kotlin">dependencies {
    <span class="hljs-comment">// ....</span>
    implementation(<span class="hljs-string">"org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.0"</span>)
    implementation(<span class="hljs-string">"io.ktor:ktor-client-core:1.6.4"</span>)
    implementation(<span class="hljs-string">"io.ktor:ktor-client-cio:1.6.4"</span>)
    implementation(<span class="hljs-string">"io.ktor:ktor-client-serialization:1.6.4"</span>)
}
</code></pre>
<p>There is one more line we need to add for <code>kotlinx.serialization</code> to work properly. You can read more about it <a target="_blank" href="https://github.com/Kotlin/kotlinx.serialization">here</a>. Let's add the following line to <code>build.gradle.kts</code> - </p>
<pre><code class="lang-kotlin">plugins {
    <span class="hljs-comment">// ...</span>
    kotlin(<span class="hljs-string">"plugin.serialization"</span>) version <span class="hljs-string">"1.5.31"</span>
}
</code></pre>
<p>Next, we need some classes to hold responses we receive from <a target="_blank" href="https://covid19api.com/">Covid19Api</a>. We'll save the classes in <code>model</code> package. Let's create them - </p>
<p>First, let's create an interface with data we need to return in <code>get-covid-stats/src/main/kotlin/model/ICovidStats.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">package</span> model

<span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">ICovidStats</span> </span>{
    <span class="hljs-keyword">val</span> newConfirmed: <span class="hljs-built_in">Int</span>
    <span class="hljs-keyword">val</span> totalConfirmed: <span class="hljs-built_in">Int</span>
    <span class="hljs-keyword">val</span> newDeaths: <span class="hljs-built_in">Int</span>
    <span class="hljs-keyword">val</span> totalDeaths: <span class="hljs-built_in">Int</span>
    <span class="hljs-keyword">val</span> newRecovered: <span class="hljs-built_in">Int</span>
    <span class="hljs-keyword">val</span> totalRecovered: <span class="hljs-built_in">Int</span>
}
</code></pre>
<p>Now, if we take a look at data returned from the <a target="_blank" href="https://documenter.getpostman.com/view/10808728/SzS8rjbc#00030720-fae3-4c72-8aea-ad01ba17adf8">endpoint</a> we see we need three classes <code>Response.kt</code>, <code>GlobalStats.kt</code> and <code>CountryStats.kt</code>. Let's create them -</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">// GlobalStats.kt</span>

<span class="hljs-keyword">package</span> model

<span class="hljs-keyword">import</span> kotlinx.serialization.SerialName
<span class="hljs-keyword">import</span> kotlinx.serialization.Serializable

<span class="hljs-meta">@Serializable</span>
<span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">GlobalStats</span></span>(
    <span class="hljs-meta">@SerialName(<span class="hljs-meta-string">"NewConfirmed"</span>)</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">val</span> newConfirmed: <span class="hljs-built_in">Int</span>,
    <span class="hljs-meta">@SerialName(<span class="hljs-meta-string">"TotalConfirmed"</span>)</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">val</span> totalConfirmed: <span class="hljs-built_in">Int</span>,
    <span class="hljs-meta">@SerialName(<span class="hljs-meta-string">"NewDeaths"</span>)</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">val</span> newDeaths: <span class="hljs-built_in">Int</span>,
    <span class="hljs-meta">@SerialName(<span class="hljs-meta-string">"TotalDeaths"</span>)</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">val</span> totalDeaths: <span class="hljs-built_in">Int</span>,
    <span class="hljs-meta">@SerialName(<span class="hljs-meta-string">"NewRecovered"</span>)</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">val</span> newRecovered: <span class="hljs-built_in">Int</span>,
    <span class="hljs-meta">@SerialName(<span class="hljs-meta-string">"TotalRecovered"</span>)</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">val</span> totalRecovered: <span class="hljs-built_in">Int</span>,
) : ICovidStats
</code></pre>
<p><code>@Serializable</code> tells <code>kotlinx.serialization</code> that this class can be parsed to/from JSON and <code>@SerialName</code> is used to indicate the JSON field name.</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">// CountryStats.kt</span>

<span class="hljs-keyword">package</span> model

<span class="hljs-keyword">import</span> kotlinx.serialization.SerialName
<span class="hljs-keyword">import</span> kotlinx.serialization.Serializable

<span class="hljs-meta">@Serializable</span>
<span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CountryStats</span></span>(
    <span class="hljs-meta">@SerialName(<span class="hljs-meta-string">"Country"</span>)</span> <span class="hljs-keyword">val</span> country: String,
    <span class="hljs-meta">@SerialName(<span class="hljs-meta-string">"CountryCode"</span>)</span> <span class="hljs-keyword">val</span> countryCode: String,
    <span class="hljs-meta">@SerialName(<span class="hljs-meta-string">"Slug"</span>)</span> <span class="hljs-keyword">val</span> slug: String,
    <span class="hljs-meta">@SerialName(<span class="hljs-meta-string">"NewConfirmed"</span>)</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">val</span> newConfirmed: <span class="hljs-built_in">Int</span>,
    <span class="hljs-meta">@SerialName(<span class="hljs-meta-string">"TotalConfirmed"</span>)</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">val</span> totalConfirmed: <span class="hljs-built_in">Int</span>,
    <span class="hljs-meta">@SerialName(<span class="hljs-meta-string">"NewDeaths"</span>)</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">val</span> newDeaths: <span class="hljs-built_in">Int</span>,
    <span class="hljs-meta">@SerialName(<span class="hljs-meta-string">"TotalDeaths"</span>)</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">val</span> totalDeaths: <span class="hljs-built_in">Int</span>,
    <span class="hljs-meta">@SerialName(<span class="hljs-meta-string">"NewRecovered"</span>)</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">val</span> newRecovered: <span class="hljs-built_in">Int</span>,
    <span class="hljs-meta">@SerialName(<span class="hljs-meta-string">"TotalRecovered"</span>)</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">val</span> totalRecovered: <span class="hljs-built_in">Int</span>,
) : ICovidStats
</code></pre>
<pre><code class="lang-kotlin"><span class="hljs-comment">// Response.kt</span>

<span class="hljs-keyword">package</span> model

<span class="hljs-keyword">import</span> kotlinx.serialization.Serializable
<span class="hljs-keyword">import</span> kotlinx.serialization.SerialName

<span class="hljs-meta">@Serializable</span>
<span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Response</span></span>(
    <span class="hljs-meta">@SerialName(<span class="hljs-meta-string">"Global"</span>)</span> <span class="hljs-keyword">val</span> global : GlobalStats,
    <span class="hljs-meta">@SerialName(<span class="hljs-meta-string">"Countries"</span>)</span> <span class="hljs-keyword">val</span> countries : List&lt;CountryStats&gt;,
)
</code></pre>
<p>Okay 🤯, these are the response models we need.</p>
<p>We also need an object which we will return from this function. Let's do that - </p>
<pre><code class="lang-kotlin"><span class="hljs-comment">// FunctionResult.kt</span>

<span class="hljs-keyword">package</span> model

<span class="hljs-keyword">import</span> kotlinx.serialization.Serializable

<span class="hljs-meta">@Serializable</span>
<span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FunctionResult</span></span>(
    <span class="hljs-keyword">val</span> isGlobal: <span class="hljs-built_in">Boolean</span>,
    <span class="hljs-keyword">val</span> newConfirmed: <span class="hljs-built_in">Int</span>,
    <span class="hljs-keyword">val</span> totalConfirmed: <span class="hljs-built_in">Int</span>,
    <span class="hljs-keyword">val</span> newDeaths: <span class="hljs-built_in">Int</span>,
    <span class="hljs-keyword">val</span> totalDeaths: <span class="hljs-built_in">Int</span>,
    <span class="hljs-keyword">val</span> newRecovered: <span class="hljs-built_in">Int</span>,
    <span class="hljs-keyword">val</span> totalRecovered: <span class="hljs-built_in">Int</span>,
)
</code></pre>
<p>We will also need a JSON Parser, Let's set up <code>kotlinx.serialization</code> json Parser - </p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> jsonParser = Json {
    isLenient = <span class="hljs-literal">true</span>
    ignoreUnknownKeys = <span class="hljs-literal">true</span>
}
</code></pre>
<p>Next, let's get the stats from the API. First, we need an HTTP Client to make the requests. Let's do that - </p>
<pre><code class="lang-kotlin">HttpClient() {
    install(JsonFeature) {
        serializer = KotlinxSerializer(json = jsonParser)
    }
}
</code></pre>
<p>Here, we also install <code>JsonFeature</code> which automatically parses the response to classes we created earlier.  Now, let's use this client to make a get request to <code>https://api.covid19api.com/summary</code>.</p>
<pre><code class="lang-kotlin">HttpClient() {
    <span class="hljs-comment">// ...</span>
}.use { client -&gt;
    <span class="hljs-keyword">val</span> response: Response = client.<span class="hljs-keyword">get</span>(<span class="hljs-string">"https://api.covid19api.com/summary"</span>)
}
</code></pre>
<p>Now let's get the country or global data from this and create a <code>FunctionResult</code> object - </p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> result: FunctionResult = response.countries.find {
    it.country.equals(country, ignoreCase = <span class="hljs-literal">true</span>) ||
            it.countryCode.equals(country, ignoreCase = <span class="hljs-literal">true</span>) ||
            it.slug.equals(country, ignoreCase = <span class="hljs-literal">true</span>)
}?.run {
    FunctionResult(
        <span class="hljs-literal">false</span>, newConfirmed, totalConfirmed, newDeaths,
        totalDeaths, newRecovered, totalRecovered
    )
} ?: response.global.run {
    FunctionResult(
        <span class="hljs-literal">true</span>, newConfirmed, totalConfirmed, newDeaths,
        totalDeaths, newRecovered, totalRecovered
    )
}
</code></pre>
<p>Let's put this information in stdout - </p>
<pre><code class="lang-kotlin">println(jsonParser.encodeToString(result))
</code></pre>
<p>Here's the complete code - </p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">import</span> io.ktor.client.*
<span class="hljs-keyword">import</span> io.ktor.client.features.json.*
<span class="hljs-keyword">import</span> io.ktor.client.features.json.serializer.*
<span class="hljs-keyword">import</span> io.ktor.client.request.*
<span class="hljs-keyword">import</span> io.ktor.utils.io.core.*
<span class="hljs-keyword">import</span> kotlinx.serialization.encodeToString
<span class="hljs-keyword">import</span> kotlinx.serialization.json.Json
<span class="hljs-keyword">import</span> model.FunctionResult
<span class="hljs-keyword">import</span> model.Response

<span class="hljs-keyword">suspend</span> <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> country = readCountryFromEnv()

    <span class="hljs-keyword">val</span> jsonParser = Json {
        isLenient = <span class="hljs-literal">true</span>
        ignoreUnknownKeys = <span class="hljs-literal">true</span>
    }

    HttpClient() {
        install(JsonFeature) {
            serializer = KotlinxSerializer(json = jsonParser)
        }
    }.use { client -&gt;
        <span class="hljs-keyword">val</span> response: Response = client.<span class="hljs-keyword">get</span>(<span class="hljs-string">"https://api.covid19api.com/summary"</span>)

        <span class="hljs-keyword">val</span> result: FunctionResult = response.countries.find {
            it.country.equals(country, ignoreCase = <span class="hljs-literal">true</span>) ||
                    it.countryCode.equals(country, ignoreCase = <span class="hljs-literal">true</span>) ||
                    it.slug.equals(country, ignoreCase = <span class="hljs-literal">true</span>)
        }?.run {
            FunctionResult(
                <span class="hljs-literal">false</span>, newConfirmed, totalConfirmed, newDeaths,
                totalDeaths, newRecovered, totalRecovered
            )
        } ?: response.global.run {
            FunctionResult(
                <span class="hljs-literal">true</span>, newConfirmed, totalConfirmed, newDeaths,
                totalDeaths, newRecovered, totalRecovered
            )
        }

        println(jsonParser.encodeToString(result))
    }
}

<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">readCountryFromEnv</span><span class="hljs-params">()</span></span>: String =
    System.getenv(<span class="hljs-string">"APPWRITE_FUNCTION_DATA"</span>)
</code></pre>
<p>Whew, that was a lot of code. Let's add our function to appwrite console (see steps in above example) and test it out.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634826677291/YYl179QTZ.png" alt="Get Covid Stats Input" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634826947659/B5dr0U5KY.png" alt="iGet Covid Stats Output" /></p>
<p>Here's what it prints - </p>
<pre><code class="lang-json">{<span class="hljs-attr">"isGlobal"</span>:<span class="hljs-literal">false</span>,<span class="hljs-attr">"newConfirmed"</span>:<span class="hljs-number">14623</span>,<span class="hljs-attr">"totalConfirmed"</span>:<span class="hljs-number">34108996</span>,<span class="hljs-attr">"newDeaths"</span>:<span class="hljs-number">197</span>,<span class="hljs-attr">"totalDeaths"</span>:<span class="hljs-number">452651</span>,<span class="hljs-attr">"newRecovered"</span>:<span class="hljs-number">0</span>,<span class="hljs-attr">"totalRecovered"</span>:<span class="hljs-number">0</span>}
</code></pre>
<p>Alright! In this article we learned the basics of Appwrite Function Service. In the next post, I'll show you how to connect an Appwrite Function to an android application. Stay tuned for that.</p>
]]></content:encoded></item><item><title><![CDATA[Kotlin Flows - collect vs collectLatest]]></title><description><![CDATA[Kotlin Coroutines and Flows make asynchronous programming really easy to understand. And in this post, we'll look at two important but slightly different operators - collect and collectLatest
Both collect and collectLatest are terminal operators i.e....]]></description><link>https://hardiksachan.com/kotlin-flows-collect-vs-collectlatest</link><guid isPermaLink="true">https://hardiksachan.com/kotlin-flows-collect-vs-collectlatest</guid><category><![CDATA[Kotlin]]></category><category><![CDATA[coroutines]]></category><category><![CDATA[flow]]></category><category><![CDATA[2Articles1Week]]></category><category><![CDATA[Android]]></category><dc:creator><![CDATA[Hardik Sachan]]></dc:creator><pubDate>Thu, 14 Oct 2021 09:55:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1634196083750/GM8vWnrf9.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Kotlin Coroutines and Flows make asynchronous programming really easy to understand. And in this post, we'll look at two important but slightly different operators - <code>collect</code> and <code>collectLatest</code></p>
<p>Both <code>collect</code> and <code>collectLatest</code> are <strong>terminal operators</strong> <em>i.e.</em> they will actually <strong>start</strong> the flow.</p>
<p>Now let's see how are they different?</p>
<p>First of all, let's build a flow</p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">intFlow</span><span class="hljs-params">()</span></span> = flow {
    (<span class="hljs-number">1</span>..<span class="hljs-number">5</span>).forEach {
        delay(<span class="hljs-number">50</span>)
        println(<span class="hljs-string">"Flowing <span class="hljs-variable">$it</span>..."</span>)
        emit(it)
    }
}
</code></pre>
<p>Please note that there is a delay of <em>50 ms</em> in the builder. </p>
<h3 id="collect"><code>collect {  }</code></h3>
<pre><code class="lang-kotlin"><span class="hljs-keyword">suspend</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    intFlow().collect {
        delay(<span class="hljs-number">100</span>)
        println(<span class="hljs-string">"\t\t\t\t<span class="hljs-variable">$it</span> received"</span>)
    }
}
</code></pre>
<p>Note that there is a delay of <em>100 ms</em> in the collector. Next, let's see the execution: </p>
<pre><code class="lang-text">Flowing 1...
                1 received
Flowing 2...
                2 received
Flowing 3...
                3 received
Flowing 4...
                4 received
Flowing 5...
                5 received
</code></pre>
<p>At first look, you might not see it but look closely. In this case, the builder <em>suspends</em> until the collector is ready for the next value. That is evident because collector delays for <em>100 ms</em> while builder only delays for <em>50</em>.</p>
<p>Now, let's see what happens with <code>collectLatest</code></p>
<h3 id="collectlatest"><code>collectLatest {  }</code></h3>
<pre><code class="lang-kotlin"><span class="hljs-keyword">suspend</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    intFlow().collectLatest {
        delay(<span class="hljs-number">100</span>)
        println(<span class="hljs-string">"\t\t\t\t<span class="hljs-variable">$it</span> received"</span>)
    }
}
</code></pre>
<pre><code class="lang-text">Flowing 1...
Flowing 2...
Flowing 3...
Flowing 4...
Flowing 5...
                5 received
</code></pre>
<p>In this case, the collector is canceled when it receives a new value from the builder and starts with that value. This is clear because, after <em>50 ms</em>, the builder provides a new value to the collector.</p>
<h1 id="how-to-choose-between-them">How to choose between them?</h1>
<p>The tradeoff between <code>collect { ... }</code> and <code>collectLatest { ... }</code> is fairly straightforward. If you need to process all the values you receive you should use <code>collect</code>, if you want only the "latest" value to be processed, use <code>collectLatest</code>.</p>
<p>This is all, if you found this article helpful, please drop a like. :)</p>
<hr />
<p>Cover Photo by <a href="https://unsplash.com/@deepakrautela?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Deepak Rautela</a> on <a href="https://unsplash.com/s/photos/thread?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></p>
]]></content:encoded></item><item><title><![CDATA[Build a Jar with Gradle]]></title><description><![CDATA[In this article, I'll show you how to build a Jar file using the Gradle build system. Let's get started.
Do you need a Fat Jar?
Before we dive into the process of building a Jar, let's address whether or not you need a fat jar. But wait,
What's a fat...]]></description><link>https://hardiksachan.com/build-a-jar-with-gradle</link><guid isPermaLink="true">https://hardiksachan.com/build-a-jar-with-gradle</guid><category><![CDATA[Java]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[gradle]]></category><dc:creator><![CDATA[Hardik Sachan]]></dc:creator><pubDate>Mon, 11 Oct 2021 14:29:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1633962401218/4tR1zVB8C.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article, I'll show you how to build a Jar file using the Gradle build system. Let's get started.</p>
<h1 id="do-you-need-a-fat-jar">Do you need a Fat Jar?</h1>
<p>Before we dive into the process of building a Jar, let's address whether or not you need a fat jar. But wait,</p>
<h4 id="whats-a-fat-jar">What's a fat jar?</h4>
<blockquote>
<p>The fat jar is the jar, which contains classes from all the libraries, on which your project depends as well as the classes of the current project.</p>
</blockquote>
<p>In other words, a fat jar is self-contained and when executed like <code>java -jar my-fat-jar.jar</code>, it will work without setting up any other dependencies.</p>
<p>Let's see how to set it up. </p>
<p>In your <code>build.gradle.kts</code> add the following lines:</p>
<pre><code class="lang-kotlin">tasks.withType&lt;Jar&gt;() {

    <span class="hljs-comment">// ...</span>

    from(sourceSets.main.<span class="hljs-keyword">get</span>().output)

    dependsOn(configurations.runtimeClasspath)
    from({
        configurations.runtimeClasspath.<span class="hljs-keyword">get</span>()
            .filter { it.name.endsWith(<span class="hljs-string">"jar"</span>) }
            .map { zipTree(it) }
    })
}
</code></pre>
<p>and that's it. This will now build a fat jar, if in case you decide you don't need it, just delete these lines.</p>
<h1 id="building-the-jar">Building the Jar</h1>
<p>Building a Jar is a fairly simple process</p>
<ul>
<li><p>Open the Gradle tab, go to <code>Tasks/build/jar</code> and create a jar file.
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633961926675/Ew1rNOL1-.png" alt="Task: build jar" /></p>
</li>
<li><p>The jar file would most likely be created at <code>/build/libs/</code>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633962172277/wgElp8ULT.png" alt="jar location" /></p>
</li>
</ul>
<h3 id="credits">Credits</h3>
<p>Cover Image: Photo by <a href="https://unsplash.com/@cameramandan83?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Dan Dennis</a> on <a href="https://unsplash.com/s/photos/jar?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></p>
]]></content:encoded></item></channel></rss>