<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Chinaza Blossom on Medium]]></title>
        <description><![CDATA[Stories by Chinaza Blossom on Medium]]></description>
        <link>https://medium.com/@chinazablossom7?source=rss-2b2bdc30f655------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*qlIcB9JZUHTfG3wz.jpg</url>
            <title>Stories by Chinaza Blossom on Medium</title>
            <link>https://medium.com/@chinazablossom7?source=rss-2b2bdc30f655------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 20:33:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chinazablossom7/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[ Understanding “Tasks” and the Back Stack in Android — The Story Behind Your App’s Journey]]></title>
            <link>https://medium.com/@chinazablossom7/understanding-tasks-and-the-back-stack-in-android-the-story-behind-your-apps-journey-fde477dd1fd0?source=rss-2b2bdc30f655------2</link>
            <guid isPermaLink="false">https://medium.com/p/fde477dd1fd0</guid>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-apps]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Chinaza Blossom]]></dc:creator>
            <pubDate>Wed, 08 Oct 2025 19:25:23 GMT</pubDate>
            <atom:updated>2025-10-08T19:25:23.503Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*axfoSKa2Tkf8XYfD" /><figcaption>Photo by <a href="https://unsplash.com/@rubaitulazad?utm_source=medium&amp;utm_medium=referral">Rubaitul Azad</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Picture this: you open Instagram, scroll through your feed, jump to messages, then wait…your friend sends you a youtube link, you tap it and boom! you’re in youtube now. Then you go back, and somehow Instagram is right where you left it.</p><p>Magic? 🪄<br> Not really. That’s the <strong><em>Android task system</em></strong> doing its job quietly behind the scenes.</p><h3>🧠 <em>The Stack Behind the Tap</em></h3><p>Imagine you’re reading a mystery novel you start with chapter 1 the introduction, then you flip to chapter 2 the plot thickens by chapter 3, you’re deep in suspense, but what if you want to revisit a clue from chapter 2? You flip back right?, that’s exactly how <strong>android’s task and back stack</strong> system works.</p><p>In Android, a <strong>task</strong> is like a storyline a sequence of screens (called <em>activities</em>) that a user navigates while trying to accomplish something. Whether it’s booking a flight, editing a photo, or sending a message, each tap opens a new chapter in the story.</p><p>These chapters don’t float around randomly. They’re stacked neatly in a structure called the <strong>back stack</strong>, where the most recent activity sits on top. When the user presses the back button, the current activity is “closed,” and the previous one resumes just like flipping back to an earlier chapter.</p><p>So, when developers talk about tasks and back stacks, they’re really talking about how Android keeps track of the user’s journey step by step, screen by screen, in a last-in, first-out (LIFO) order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jIXjrV6sc17zrG8rf0ALVQ.jpeg" /><figcaption>Android Back Stack</figcaption></figure><p>Imagine a task as a deck of cards:</p><ul><li>Each <strong>card</strong> is an <strong>Activity</strong>.</li><li>The <strong>top card</strong> is what’s currently visible.</li><li>When you press “Back,” Android just pops the top card off.</li></ul><p>Simple, right? Until you realize android gives you <strong><em>superpowers</em> </strong>to control how these cards behave, and that’s where things get intresting.</p><h3>🎢 The Task Lifecycle</h3><p>Picture this: you’re browsing recipes in an app (Task A), then suddenly hop over to Instagram (Task B).</p><ul><li>When you hit Home, Task A quietly moves to the <strong>background </strong>paused but not forgotten.</li><li>Instagram (Task B) takes over the <strong>foreground</strong>, becoming your focus.</li><li>Later, you open your recipe app again. Android doesn’t rebuild everything, it simply <strong>restores Task A</strong>, exactly where you left off.</li></ul><p>It’s like switching browser tabs: your previous one isn’t deleted, just waiting in the background.</p><p>That’s Android’s magic, smooth task juggling.</p><h3>🏡 Back Press on Android 12+ “A Subtle but Important Change”</h3><p>On Android 11 and below, when you pressed <strong>Back</strong> from your app’s launcher activity (the one declared with an <a href="https://developer.android.com/reference/android/content/IntentFilter">intent filter</a> with both <a href="https://developer.android.com/reference/android/content/Intent#ACTION_MAIN"><strong>ACTION_MAIN</strong></a> and <a href="https://developer.android.com/reference/android/content/Intent#CATEGORY_LAUNCHER"><strong>CATEGORY_LAUNCHER</strong></a>), the system simply <strong>finishes </strong>the activity.</p><p>But starting with <strong>Android 12</strong>, pressing Back from that root launcher doesn’t kill the app anymore. Instead, it <strong>moves the app to the background</strong>, just like pressing the Home button.</p><p>This makes relaunching faster becaause your app stays warm and ready.</p><p>👉 <strong>Tip for devs: </strong>In the old days of Android development, overriding <strong>onBackPressed()</strong> felt like a rite of passage. You’d intercept the back button, finish the activity, and boom…navigation handled but as android evolved, so did its expectations for user experience,</p><p>The <strong>AndroidX Activity APIs </strong>are the modern, lifecycle aware way to handle back navigation, These APIs don’t just replace <strong>onBackPressed()</strong>; they <em>respect</em> the system’s navigation model, defer to predictive gestures, and play nicely with multi-window environments.</p><p>Here’s the key shift:</p><ul><li><strong>Old way</strong>: <strong>onBackPressed()</strong> → <strong>finish()</strong> → abrupt exit.</li><li><strong>New way</strong>: <strong>super.onBackPressed()</strong> → system decides → smoother UX.</li></ul><p>By calling <strong>super.onBackPressed()</strong>, your app doesn’t just “quit”; it gracefully moves to the background when appropriate, preserving state and aligning with how users expect apps to behave across Android versions.<br>So if you’re still overriding <strong>onBackPressed()</strong> and calling <strong>finish()</strong>, stop doing that use <strong>super.onBackPressed()</strong> instead.</p><h3>📚 Managing Multiple Activities and Instances</h3><p>Let’s say your app has these activities:</p><ol><li><strong>MainActivity</strong> ⇨ Home screen</li><li><strong>DetailActivity</strong> ⇨ Shows an item</li><li><strong>ProfileActivity</strong> ⇨ User profile</li></ol><p>Normally, launching them one after another stacks them like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qgh6AEWhndqayGJHpgFfzQ.jpeg" /></figure><p>Pressing Back would take you:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zsYwVd6UjcwcWi8c0gIRcA.jpeg" /></figure><p>But then you add a new feature; opening someone’s profile from a notification.<br>You click the notification, and…pause, wait…should Android reuse the old task, or start a new one?</p><p>That’s where <strong>launch modes</strong> and <strong>intent flags</strong> come in.</p><h3>🧩 Understanding Launch Modes</h3><p>Every activity has a <strong>launchMode</strong>, which defines how Android handles it when it’s started. Meet the Launch Modes:</p><h4>1. Standard</h4><p>In Android, when you start an activity, the system needs to decide <strong>how</strong> to launch it; whether to reuse an existing instance or create a new one. The <strong>standard</strong> mode is the default behavior, and it’s the most straightforward:</p><ul><li><strong>Every time</strong> an activity is started, the system creates a <strong>new instance</strong> of it.</li><li>This new instance is added to the <strong>back stack</strong> of the task that initiated it.</li><li>You can have <strong>multiple instances</strong> of the same activity even across different tasks, and within a single task, you can have <strong>several copies</strong> of the same activity stacked up.</li></ul><p>Let’s say your app has Activity A, and it starts Activity B. If B is set to <strong>&quot;standard&quot;</strong>:</p><ul><li>A new instance of B is created and pushed onto the stack.</li><li>If B starts another B, another instance is created so you could end up with <strong>A ⇾ B ⇾ B ⇾ B.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9eMGBCqGSrmDhclfARgAnA.jpeg" /><figcaption>LaunchMode: Standard</figcaption></figure><p>This behavior is useful when each instance of the activity represents a <strong>distinct state or context, </strong>like viewing different emails or articles.</p><h4>2. SingleTop</h4><p>Activities are stacked like pancakes; each new one layered on top of the last. But what if the top pancake is already the flavor you want? That’s where <strong>&quot;singleTop&quot;</strong> comes in; If an activity is already sitting <strong>at the top</strong> of the back stack and you try to launch it again, Android says, “Wait—we already have this!” and instead calls <strong>onNewIntent()</strong> on the existing instance. This means no duplicate activity on the stack, the activity handles the new intent without restarting and the stack remains clean and efficient.</p><p>Let’s say your stack looks like this: <strong>A ⇾ B ⇾ C ⇾ D</strong> (D is on top); Now, an intent arrives to launch <strong>D</strong> again:</p><ul><li>If D is <strong>&quot;standard&quot;</strong>: You get <strong>A ⇾ B ⇾ C ⇾ D ⇾ D</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CYy5rNz4oT2R859uv-FiiA.jpeg" /><figcaption>LaunchMode: Standard</figcaption></figure><ul><li>If D is <strong>&quot;singleTop&quot;</strong>: You stay at <strong>A ⇾ B ⇾ C ⇾ D</strong>, and D handles the intent via <strong>onNewIntent()</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*saMxHN0g2sWGKot3iiutuA.jpeg" /></figure><p>But if the intent is for <strong>B</strong>, even with <strong>&quot;singleTop&quot;</strong>:</p><ul><li>A new instance of B is added: <strong>A ⇾ B ⇾ C ⇾ D ⇾ B</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BG2HSo4qbRgoSq9Fe2itQw.jpeg" /><figcaption>LaunchMode: SingleTop</figcaption></figure><ul><li>Because B wasn’t on top, Android treats it like a fresh launch.</li></ul><p>SingleTop is perfect for stuff like notifications why open multiple copies of the same screen when there can be only one also for deep links that should refresh the current view.</p><h4>3. SingleTask</h4><p>Sometimes, you want an activity to stand alone, like a <strong>home base</strong> that users return to no matter where they are. When an activity is set to <strong>&quot;singleTask&quot;</strong>, Android ensures <strong>only one instance</strong> of it exists across the system. If it’s already running, Android <strong>routes the intent</strong> to that instance via <strong>onNewIntent()</strong>and here’s the kicker <strong>all activities above it in the stack are destroyed</strong> yup yup; clean slate.</p><p>Imagine a stack like this: <strong>A ⇾ B ⇾ C ⇾ D</strong> (D is on top)</p><p>Now, an intent arrives for <strong>Activity B</strong>, which is set to <strong>&quot;singleTask&quot;</strong>:</p><ul><li>Android finds the existing B.</li><li>It <strong>destroys C and D</strong>.</li><li>B receives the intent via <strong>onNewIntent()</strong>.</li><li>The stack becomes: <strong>A ⇾ B</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o77q3vdhLo2iJk0Ia_C7nQ.jpeg" /><figcaption>Launch mode: SingleTask</figcaption></figure><p>This is mode perfect for activities like; a dashboard or home screen, a login screen that should reset the flow, a browser tab that always opens in its own task.</p><h4>4. SingleInstance</h4><p>Some activities don’t like company. They don’t want to be stacked, shared, or shuffled. They want their own space, their own vibe. That’s the <strong>&quot;singleInstance&quot;</strong> launch mode or extreme introvert mode 😅. In this mode only <strong>one instance</strong> of the activity exists; ever, and it lives in its <strong>own task</strong>, completely isolated any activity it starts opens in a <strong>separate task</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wqht7SHl65B-6HkAOnluCQ.jpeg" /><figcaption>LaunchMode: SingleInstance</figcaption></figure><ul><li>C is launched and placed in its <strong>own isolated task</strong>.</li><li>If C starts ActivityD, D is <strong>not added to C’s task, </strong>it opens in a <strong>new task</strong>.</li><li>C remains the <strong>only activity</strong> in its own task .</li></ul><h4><strong>5. singleInstancePerTask</strong></h4><p>This launch mode is like &quot;<strong>singleTask</strong>&quot; but with a twist. It ensures that <strong>only one instance</strong> of the activity exists <strong>per task</strong>, and it must be the <strong>root</strong> of that task. However, unlike &quot;<strong>singleTask</strong>&quot;, you can have <strong>multiple tasks</strong>, each with its own instance of the activity if you use special intent flags. So the activity is always the <strong>first (root)</strong> activity in its task, but you can’t stack other activities <strong>above it</strong> in the <strong>same task, </strong>though you can create <strong>multiple instances</strong> of it; but only in <strong>separate tasks</strong> using <strong>FLAG_ACTIVITY_MULTIPLE_TASK</strong> or <strong>FLAG_ACTIVITY_NEW_DOCUMENT</strong></p><p>Let’s say Activity <strong>A</strong> is set to <strong>singleInstancePerTask</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3dW27newHNup5eq0JPiotg.jpeg" /><figcaption>LaunchMode: SingleInstancePerTask</figcaption></figure><p>A is the <strong>root</strong> and <strong>only</strong> activity in this task.</p><p>So if Second Launch (with intent flags):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C0hi73nIFFPCQBpu5kf0iA.jpeg" /><figcaption>LaunchMode: SingleInstancePerTask</figcaption></figure><ul><li>A new task is created with a <strong>new instance</strong> of A.</li><li>This only works if you use <strong>FLAG_ACTIVITY_MULTIPLE_TASK</strong> or <strong>FLAG_ACTIVITY_NEW_DOCUMENT</strong>.</li></ul><p>If <strong>A </strong>tries to start <strong>B</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ilV8BseGMxLiL4GrrGY4aw.jpeg" /></figure><ul><li>B <strong>cannot</strong> be added to A’s task.</li><li>It opens in a <strong>separate task</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5g3Vn7b36_5dWwhX442ZWg.jpeg" /></figure><p>Let’s say your current stack is: <strong>A ⇾ B ⇾ C</strong>.</p><p>Now you launch <strong>D</strong>, and D is declared as <strong>singleInstancePerTask</strong>.</p><ul><li>D <strong>does not join</strong> the existing stack.</li><li>Instead, Android creates a <strong>new task</strong> with D as the <strong>root and only</strong> activity.</li><li>You <strong>cannot</strong> stack other activities above D in Task 2.</li><li>If you launch D again (with intent flags), a <strong>new instance</strong> of D in a <strong>separate task</strong>, thanks to <strong>FLAG_ACTIVITY_MULTIPLE_TASK</strong> or <strong>FLAG_ACTIVITY_NEW_DOCUMENT</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eFWXux8yuiZXEcD5ld0kzw.jpeg" /></figure><h3>🏷️ Intent Flags: Launch Modes, but Dynamic</h3><p>You can also control task behavior on the fly with intent flags like:</p><ul><li><strong>FLAG_ACTIVITY_NEW_TASK</strong> → Starts in a new task (like <strong>singleTask</strong>).</li><li><strong>FLAG_ACTIVITY_SINGLE_TOP</strong> → Reuses the current top instance (like <strong>singleTop</strong>).</li><li><strong>FLAG_ACTIVITY_CLEAR_TOP</strong> → Brings an existing activity to the top, clearing others above it.</li></ul><p>A neat combo is:</p><pre>Intent(this, MainActivity::class.java).apply {<br>    flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK<br>}</pre><h3>💡 Task Affinity: Who Belongs Where?</h3><p>By default, all activities in your app share the same <strong>taskAffinity; </strong>meaning they prefer to live in the same task but sometimes, you want to mix things up.</p><p>For example, say your weather feature can be launched from both a travel app and a standalone shortcut. You can give it a different <strong>taskAffinity </strong>so that it joins whichever app started it; or even reassign itself to another task later (if <strong>allowTaskReparenting=true</strong>).</p><p>Affinities are like friend groups for activities; they define where each screen feels at home.</p><h3>🧹 Clearing the Stack (Because Users Move On)</h3><p>Android assumes that after a long break, users want a clean slate. So, if they leave your task for too long, the system may clear everything except the <strong>root activity</strong>.</p><p>You can customize that behavior using these attributes:</p><p><strong>alwaysRetainTaskState</strong> ⇾ Keeps all activities even after a long time away</p><p><strong>clearTaskOnLaunch⇾ </strong>Clears everything when the task is relaunched</p><p><strong>finishOnTaskLaunch</strong> <strong>⇾ </strong>Closes a specific activity when the task is relaunched</p><p>These are small toggles that make a big difference in how “sticky” your navigation feels.</p><p>What’s the weirdest back-stack bug you’ve ever faced? Drop it in the comments ; let’s laugh and cry together!</p><p>You can find more details on this topic here <strong>⇾ </strong><a href="https://developer.android.com/guide/components/activities/tasks-and-back-stack"><strong>Task And Backstack</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fde477dd1fd0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Null Saftey in Kotlin: Eliminating the Billion-Dollar Mistake]]></title>
            <link>https://medium.com/@chinazablossom7/understanding-null-saftey-in-kotlin-eliminating-the-billion-dollar-mistake-9380fd8c22a5?source=rss-2b2bdc30f655------2</link>
            <guid isPermaLink="false">https://medium.com/p/9380fd8c22a5</guid>
            <category><![CDATA[null-safety]]></category>
            <category><![CDATA[nullpointerexception]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Chinaza Blossom]]></dc:creator>
            <pubDate>Fri, 28 Jun 2024 17:01:30 GMT</pubDate>
            <atom:updated>2024-06-29T13:57:51.425Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B5LgPqsLOdOMIww7xp7hfw.png" /></figure><p>Welcome to our exciting interview with Kotlin, the modern and expressive programming language that’s taking the tech world by storm! Today, we’re delving deep into one of its most powerful features — null safety. Buckle up as we uncover the secrets behind eliminating the infamous billion-dollar mistake.</p><p><strong>Interviewer:</strong> Kotlin, thanks for joining us today! Everyone’s talking about how you tackle null safety. Can you tell us why this is such a big deal?</p><p><strong>Kotlin:</strong> Absolutely! Null safety is crucial because null references have been the source of countless bugs and crashes in software development, famously called the “Billion-Dollar Mistake” by <a href="https://en.wikipedia.org/wiki/Tony_Hoare">Tony Hoare</a>. In languages like Java, accessing a null reference leads to a <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/NullPointerException.html">NullPointerException (NPE)</a>, causing unexpected crashes. I aim to eliminate these by differentiating between nullable and non-nullable types right at the language level.</p><p><strong>Interviewer:</strong> That sounds incredible. First, can you explain what null and non-null types are?</p><p><strong>Kotlin:</strong> Of course! Imagine you have a cup. If it’s a non-nullable cup, it’s guaranteed to always have something in it, like coffee or your favorite beverage. You can always rely on it having coffee when you need a sip.</p><pre>var cupOfCoffee: String = &quot;Coffee&quot;<br>// cupOfCoffee = null // Compilation error: Null cannot be a value of a non-null type String</pre><p>On the other hand, a nullable cup might sometimes be empty and you need to check if there’s coffee in it before you take a sip, just to be safe, you must declare a variable as nullable by adding a ? to its type:</p><pre>var cupOfCoffee: String? = &quot;Coffee&quot;<br>cupOfCoffee = null // Perfectly fine and safe</pre><p>In coding terms, non-nullable types are like cups that must always contain coffee, while nullable types are like cups that might sometimes be empty, and you need to handle them carefully to avoid disappointment. In Kotlin, types are non-nullable by default. This means you cannot assign null to a variable of a non-nullable type, ensuring you catch potential null issues at compile time If you attempt to do so, the compiler will throw an error, preventing potential null reference issues right from the start.</p><p><strong>Interviewer:</strong> Interesting! So, how do you deal with nullable types securely and safely access properties or methods of nullable types without risking an NPE?</p><p><strong>Kotlin:</strong> I introduce the safe call operator ?. It allows you to safely access properties and methods of nullable objects without risk of a NullPointerExceptionWhen you use a safe call, i’ll check for null before performing the operation. If the object is null, the call returns null instead of throwing an exception.</p><pre>var cupOfCoffee: String? = &quot;Coffee&quot;<br>println(cupOfCoffee?.length) // will return 6<br><br>cupOfCoffee = null<br>println(cupOfCoffee?.length) // will return `null`</pre><p><strong>Interviewer:</strong> Let’s make this more concrete. Can you give us an example where safe calls are useful?</p><p><strong>Kotlin:</strong> Sure! Imagine you want to check if there’s coffee in a cup before taking a sip. You only drink if the cup is not empty. Lets take another instance imagine an app managing user profiles. A user’s profile might include optional fields like a middle name. Using nullable types and safe calls, you can handle these fields elegantly.</p><pre>data class UserProfile(val firstName: String, val middleName: String? = null, val lastName: String)<br><br>fun printUserProfile(user: UserProfile) {<br>    println(&quot;First Name: ${user.firstName}&quot;)<br>    val middleNameLength = user.middleName?.length // Safe call to get length if middleName is not null<br>    println(&quot;Middle Name: ${user?.middleName ?: &quot;N/A&quot;}&quot;) // Elvis operator for default value<br>    println(&quot;Middle Name Length: $middleNameLength&quot;)<br>    println(&quot;Last Name: ${user.lastName}&quot;)<br>}<br><br>fun main() {<br><br>    printUserProfile(UserProfile(firstName = &quot;John&quot;, lastName = &quot;Doe&quot;))<br><br>/*  Output:<br>    First Name: John<br>    Middle Name: N/A<br>    Middle Name Length: null<br>    Last Name: Doe<br>*/<br>    printUserProfile(UserProfile(firstName = &quot;John&quot;, middleName = &quot;Paul&quot;, lastName = &quot;Doe&quot;))<br>/*<br>     Output:<br>      First Name: John<br>      Middle Name: Paul<br>      Middle Name Length: 4<br>      Last Name: Doe<br> */<br><br>}</pre><p><strong>Interviewer:</strong> I’m sorry The Elvis operator ???, wow what a catchy name! How does it work?</p><p><strong>Kotlin:</strong> Ahh yes The Elvis operator ?: It provides a default value if the expression on the left is null. It&#39;s a concise way to handle nullable values.</p><pre>var cupOfCoffee: String? = &quot;Coffee&quot;<br>println(cupOfCoffee?.length ?: 0) // length is 0 if it is null<br>// Output in this example will be 6</pre><p><strong>Interviewer:</strong> That’s very handy. How about when handling API responses with potentially missing fields?</p><p><strong>Kotlin:</strong> Great example! When handling API responses, fields might be missing or null. The Elvis operator ensures your app remains stable by providing default values.</p><pre>fun parseApiResponse(response: Map&lt;String, Any?&gt;) {<br>    val status = response[&quot;status&quot;] as? String ?: &quot;Unknown&quot;<br>    val data = response[&quot;data&quot;] as? String ?: &quot;No data available&quot;<br>    println(&quot;Status: $status&quot;)<br>    println(&quot;Data: $data&quot;)<br>}</pre><p><strong>Interviewer:</strong> What if a developer is absolutely sure a value isn’t null? Can they bypass the checks?</p><p><strong>Kotlin:</strong> Of course!, they can use the non-null assertion operator !! to cast a nullable type to a non-nullable type. But caution is needed with this one if the value is null, it throws an NPE.</p><pre>var cupOfCoffee: String? = &quot;Coffee&quot;<br>println(cupOfCoffee!!.length) // Throws a `NullPointerException` if cupOfCoffe is null else 6</pre><p><strong>Interviewer:</strong> That seems risky. When would this be appropriate?</p><p><strong>Kotlin:</strong> It’s useful in scenarios where you’ve validated input and are certain it’s not null. For example, user input validation.</p><pre>fun processUserInput(input: String?) {<br>    require(!input.isNullOrBlank()) { &quot;Invalid input&quot; }<br>    val trimmedInput = input!!.trim() // Safe to use !! after validation<br>    println(&quot;Processed input: $trimmedInput&quot;)<br> <br>   }</pre><p><strong>Interviewer:</strong> How do you handle type casting safely?</p><p><strong>Kotlin:</strong> I support safe casting with as?, which returns null if the cast fails, preventing ClassCastException.</p><pre>  val language: Any = &quot;Kotlin&quot;<br>  val value: String? = language as? String // language is safely cast to String or null<br>    <br>  val number: Any = &quot;123&quot;<br>  val intNumber: Int? = number as? Int // null since number is not an Int</pre><p><strong>Interviewer:</strong> Okay what about when parsing JSON with mismatched types?</p><p><strong>Kotlin:</strong> When parsing JSON, types might not match expectations. Safe casting ensures mismatched types don’t crash your app.</p><pre>  fun parseJson(json: Map&lt;String, Any&gt;) {<br>      val age = json[&quot;age&quot;] as? Int ?: 0 // Use default value if not an Int<br>      println(&quot;Age: $age&quot;)<br>  }</pre><p><strong>Interviewer:</strong> These features are amazing. What are some best practices for null safety in Kotlin?</p><p><strong>Kotlin:</strong> Here are a few:</p><ol><li><strong>Use Nullable Types Wisely</strong>: Reserve nullable types for variables that can indeed be null. Stick to non-nullable types to ensure data integrity.</li><li><strong>Embrace Safe Calls and the Elvis Operator</strong>: These operators reduce boilerplate null checks and keep your code clean and safe.</li><li><strong>Use </strong><a href="https://kotlinlang.org/docs/scope-functions.html#let"><strong>let</strong></a><strong> for Null Checks</strong>: The <a href="https://kotlinlang.org/docs/scope-functions.html#let">let</a> function executes a block of code only if the variable is not null.</li><li><strong>Leverage </strong><a href="https://kotlinlang.org/docs/scope-functions.html#apply"><strong>apply</strong></a><strong> for Configuration</strong>: Use <a href="https://kotlinlang.org/docs/scope-functions.html#apply">apply</a> to configure nullable objects when they are not null.</li><li><strong>Take Advantage of </strong><a href="https://kotlinlang.org/docs/scope-functions.html#takeif-and-takeunless"><strong>takeIf</strong></a><strong> and </strong><a href="https://kotlinlang.org/docs/scope-functions.html#takeif-and-takeunless"><strong>takeUnless</strong></a>: These functions help conditionally check and return null if conditions are not met.</li><li><strong>Design APIs for Null Safety</strong>: Use default parameters when designing APIs, and provide non-null types in your APIs to encourage proper handling of nulls.</li></ol><p><strong>Interviewer:</strong> Kotlin, thank you for the insightful discussion! Any final thoughts for our readers?</p><p><strong>Kotlin:</strong> Embrace null safety to write robust, maintainable code that gracefully handles nulls. Use the tools I provide to eliminate the billion-dollar mistake from your codebase. Happy coding, everyone!</p><p><strong>Interviewer:</strong> Share your thoughts and experiences with null safety in Kotlin in the comments below. Let’s code with confidence and make our applications rock-solid!. Found this article helpful? Follow for more insights into Kotlin and modern software development practices! Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9380fd8c22a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>