<?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 Baljeet Singh on Medium]]></title>
        <description><![CDATA[Stories by Baljeet Singh on Medium]]></description>
        <link>https://medium.com/@ibaljeet?source=rss-ee347576cb25------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*g_pmpNIipL21pEQUJi7M3g.jpeg</url>
            <title>Stories by Baljeet Singh on Medium</title>
            <link>https://medium.com/@ibaljeet?source=rss-ee347576cb25------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 20:51:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ibaljeet/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[How I Cut My Claude Code Bill by 90%: A Practical Guide]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://ibaljeet.medium.com/how-i-cut-my-claude-code-bill-by-90-a-practical-guide-49b3a396db4d?source=rss-ee347576cb25------2"><img src="https://cdn-images-1.medium.com/max/2600/0*uXMc5arweTvXE_LW" width="3508"></a></p><p class="medium-feed-snippet">I was burning through my Claude Code enterprise budget way too fast. Every debugging session where I fed it stack traces and pointed it at&#x2026;</p><p class="medium-feed-link"><a href="https://ibaljeet.medium.com/how-i-cut-my-claude-code-bill-by-90-a-practical-guide-49b3a396db4d?source=rss-ee347576cb25------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://ibaljeet.medium.com/how-i-cut-my-claude-code-bill-by-90-a-practical-guide-49b3a396db4d?source=rss-ee347576cb25------2</link>
            <guid isPermaLink="false">https://medium.com/p/49b3a396db4d</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Baljeet Singh]]></dc:creator>
            <pubDate>Tue, 31 Mar 2026 18:19:54 GMT</pubDate>
            <atom:updated>2026-03-31T18:46:43.073Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Why I Started Using Sealed Interfaces in Kotlin (And You Should Too)]]></title>
            <link>https://levelup.gitconnected.com/why-i-started-using-sealed-interfaces-in-kotlin-and-you-should-too-2db97522750f?source=rss-ee347576cb25------2</link>
            <guid isPermaLink="false">https://medium.com/p/2db97522750f</guid>
            <category><![CDATA[android-apps]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Baljeet Singh]]></dc:creator>
            <pubDate>Wed, 01 Oct 2025 14:44:53 GMT</pubDate>
            <atom:updated>2025-10-01T14:44:53.305Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DHJOXJ3h2wDZAhPu" /><figcaption>Photo by <a href="https://unsplash.com/@ikukevk?utm_source=medium&amp;utm_medium=referral">Kevin Ku</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A few months back, I was building an app that handles different types of user notifications. I had push notifications, email alerts, and SMS messages. My first attempt looked like this:</p><pre>interface Notification {<br>    fun send()<br>}<br><br>class PushNotification(val title: String) : Notification {<br>    override fun send() {<br>        println(&quot;Sending push: $title&quot;)<br>    }<br>}<br>class EmailNotification(val subject: String) : Notification {<br>    override fun send() {<br>        println(&quot;Sending email: $subject&quot;)<br>    }<br>}</pre><p>This worked fine until I needed to handle each notification type differently in my UI. I ended up with some missing checks everywhere. That&#39;s when I used sealed interfaces.</p><h3>What Are Sealed Interfaces?</h3><p>Think of sealed interfaces like a restricted club. Only specific classes can join, and you know exactly who all the members are at compile time.</p><p>Here’s the same notification system using sealed interfaces:</p><pre>sealed interface Notification {<br>    fun send()<br>}<br><br>data class PushNotification(val title: String, val body: String) : Notification {<br>    override fun send() {<br>        println(&quot;📱 Push: $title&quot;)<br>    }<br>}<br>data class EmailNotification(val subject: String, val recipient: String) : Notification {<br>    override fun send() {<br>        println(&quot;📧 Email to $recipient: $subject&quot;)<br>    }<br>}<br>data class SmsNotification(val message: String, val phoneNumber: String) : Notification {<br>    override fun send() {<br>        println(&quot;📱 SMS to $phoneNumber: $message&quot;)<br>    }<br>}</pre><p>The magic happens when you use them with when expressions:</p><pre>fun handleNotification(notification: Notification) {<br>    when (notification) {<br>        is PushNotification -&gt; {<br>            // Show in notification bar<br>            showInNotificationBar(notification.title, notification.body)<br>        }<br>        is EmailNotification -&gt; {<br>            // Log email sent<br>            logEmailSent(notification.recipient)<br>        }<br>        is SmsNotification -&gt; {<br>            // Track SMS cost<br>            trackSmsCost(notification.phoneNumber)<br>        }<br>        // No else needed! Kotlin knows these are all possibilities<br>    }<br>}</pre><h3>Real Example: API Response Handling</h3><p>Here’s where sealed interfaces really shine. I was working with an API that could return success, error, or loading states:</p><pre>sealed interface ApiResponse&lt;out T&gt; {<br>    data class Success&lt;T&gt;(val data: T) : ApiResponse&lt;T&gt;<br>    data class Error(val message: String, val code: Int) : ApiResponse&lt;Nothing&gt;<br>    object Loading : ApiResponse&lt;Nothing&gt;<br>}</pre><p>Now handling API responses is clean and safe:</p><pre>fun displayUserProfile(response: ApiResponse&lt;User&gt;) {<br>    when (response) {<br>        is ApiResponse.Success -&gt; {<br>            val user = response.data<br>            nameText.text = user.name<br>            emailText.text = user.email<br>            hideLoading()<br>        }<br>        is ApiResponse.Error -&gt; {<br>            showError(&quot;Failed to load profile: ${response.message}&quot;)<br>            hideLoading()<br>        }<br>        is ApiResponse.Loading -&gt; {<br>            showLoading()<br>        }<br>    }<br>}</pre><p>The compiler forces you to handle every case. No more forgotten error states!</p><h3>Payment Methods Example</h3><p>Let me show you another real scenario. I was building a checkout flow with different payment methods:</p><pre>sealed interface PaymentMethod {<br>    data class CreditCard(<br>        val number: String,<br>        val expiryMonth: Int,<br>        val expiryYear: Int,<br>        val cvv: String<br>    ) : PaymentMethod<br>    <br>    data class PayPal(val email: String) : PaymentMethod<br>    <br>    data class BankTransfer(<br>        val accountNumber: String,<br>        val routingNumber: String<br>    ) : PaymentMethod<br>    <br>    object ApplePay : PaymentMethod<br>}</pre><p>Processing payments becomes straightforward:</p><pre>fun processPayment(method: PaymentMethod, amount: Double) {<br>    when (method) {<br>        is PaymentMethod.CreditCard -&gt; {<br>            chargeCreditCard(method.number, method.cvv, amount)<br>        }<br>        is PaymentMethod.PayPal -&gt; {<br>            initiatePayPalPayment(method.email, amount)<br>        }<br>        is PaymentMethod.BankTransfer -&gt; {<br>            processBankTransfer(method.accountNumber, method.routingNumber, amount)<br>        }<br>        is PaymentMethod.ApplePay -&gt; {<br>            startApplePayFlow(amount)<br>        }<br>    }<br>}</pre><h3>Why Not Just Use Regular Interfaces?</h3><p>You might ask, “Why not just use normal interfaces?” Here’s the problem:</p><p>With regular interfaces, anyone can implement them anywhere in your codebase. You lose control. With sealed interfaces, you define all implementations in the same file. The compiler knows the complete list.</p><p>This means:</p><ul><li><strong>No missing cases</strong> in when expressions</li><li><strong>Better refactoring</strong> — add a new type and the compiler shows you everywhere you need to update</li><li><strong>Cleaner code</strong> — no defensive programming with else branches</li></ul><h3>File Upload States (Another Real Example)</h3><p>Here’s how I handle file uploads in my apps:</p><pre>sealed interface UploadState {<br>    object Idle : UploadState<br>    data class Uploading(val progress: Int) : UploadState<br>    data class Success(val fileUrl: String) : UploadState<br>    data class Failed(val error: String) : UploadState<br>}</pre><p>My UI updates automatically based on state:</p><pre>fun updateUploadUI(state: UploadState) {<br>    when (state) {<br>        is UploadState.Idle -&gt; {<br>            uploadButton.isEnabled = true<br>            progressBar.hide()<br>        }<br>        is UploadState.Uploading -&gt; {<br>            uploadButton.isEnabled = false<br>            progressBar.show()<br>            progressBar.progress = state.progress<br>        }<br>        is UploadState.Success -&gt; {<br>            uploadButton.isEnabled = true<br>            progressBar.hide()<br>            showSuccess(&quot;File uploaded: ${state.fileUrl}&quot;)<br>        }<br>        is UploadState.Failed -&gt; {<br>            uploadButton.isEnabled = true<br>            progressBar.hide()<br>            showError(state.error)<br>        }<br>    }<br>}</pre><h3>Quick Tips</h3><p><strong>Do this:</strong></p><pre>sealed interface Result&lt;out T&gt; {<br>    data class Success&lt;T&gt;(val data: T) : Result&lt;T&gt;<br>    data class Error(val exception: Exception) : Result&lt;Nothing&gt;<br>}</pre><p><strong>Not this:</strong></p><pre>// Regular interface - anyone can implement it<br>interface Result&lt;out T&gt; {<br>    // ...<br>}</pre><p><strong>Use data classes</strong> for implementations that hold data. Use object for singleton states like Loading or Idle.</p><h3>When to Use Sealed Interfaces</h3><p>I use sealed interfaces when:</p><ul><li>I have a fixed set of related types</li><li>I want exhaustive when expressions</li><li>I’m modeling state machines (loading, success, error)</li><li>I’m handling different data types from APIs</li><li>I want the compiler to help me catch missing cases</li></ul><h3>Wrapping Up</h3><p>Sealed interfaces changed how I write Kotlin code. They make impossible states impossible and help me write more reliable apps. The compiler becomes your friend, catching errors before they reach users.</p><p>Try replacing your next enum or interface with a sealed interface. Your future self will thank you when you add a new case and the compiler shows you exactly where to update your code.</p><p>What’s your experience with sealed interfaces? Have you found other creative ways to use them? I’d love to hear about it!</p><p>For any questions or queries, let’s connect on LinkedIn</p><p><a href="https://www.linkedin.com/in/devbaljeet/">https://www.linkedin.com/in/devbaljeet/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2db97522750f" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/why-i-started-using-sealed-interfaces-in-kotlin-and-you-should-too-2db97522750f">Why I Started Using Sealed Interfaces in Kotlin (And You Should Too)</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Value Classes: Stop Wrapping Everything in Regular Classes]]></title>
            <link>https://proandroiddev.com/kotlin-value-classes-stop-wrapping-everything-in-regular-classes-2ee2626afb0d?source=rss-ee347576cb25------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ee2626afb0d</guid>
            <category><![CDATA[android-apps]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Baljeet Singh]]></dc:creator>
            <pubDate>Sun, 28 Sep 2025 14:22:13 GMT</pubDate>
            <atom:updated>2025-09-28T14:22:13.024Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been working with Kotlin for a few years now, and one feature that really changed how I write code is value classes. They’re not talked about enough, but they solve a real problem we all face: how do you make your code safer without making it slower?</p><p>Let me show you what I mean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ckBrLzs6KcoMN9fW" /><figcaption>Photo by <a href="https://unsplash.com/@louis993546?utm_source=medium&amp;utm_medium=referral">Louis Tsai</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The Problem We All Have</h3><p>Picture this: you’re building an app that handles user accounts. You have user IDs, product IDs, order IDs everywhere. All of them are just integers, but they mean different things.</p><pre>fun processOrder(userId: Int, productId: Int, orderId: Int) {<br>    // What if someone passes these in the wrong order?<br>    // The compiler won&#39;t catch it!<br>}<br><br>// This compiles fine but is totally wrong<br>processOrder(productId = 123, userId = 456, orderId = 789)</pre><p>See the problem? The compiler can’t help us here. All three parameters are integers, so any order works. But in reality, mixing them up breaks everything.</p><h3>The Old Way: Regular Classes</h3><p>Before value classes, we’d solve this with wrapper classes:</p><pre>data class UserId(val value: Int)<br>data class ProductId(val value: Int) <br>data class OrderId(val value: Int)<br><br>fun processOrder(userId: UserId, productId: ProductId, orderId: OrderId) {<br>    println(&quot;Processing order ${orderId.value} for user ${userId.value}&quot;)<br>}<br>// Now this won&#39;t compile - much better!<br>// processOrder(ProductId(123), UserId(456), OrderId(789)) // Wrong order = compile error</pre><p>This works great for safety. But there’s a catch — performance.</p><p>Every time you create UserId(123), you&#39;re actually creating a real object in memory. That object has overhead. If you&#39;re doing this thousands of times in a loop, it adds up.</p><p>I remember profiling an app where we wrapped everything in data classes like this. The garbage collector was going crazy cleaning up all these tiny wrapper objects.</p><h3>Enter Value Classes</h3><p>Kotlin introduced us to value classes. They give you the safety of wrapper classes with zero runtime overhead.</p><p>Here’s the magic:</p><pre>@JvmInline<br>value class UserId(val value: Int)<br>@JvmInline  <br>value class ProductId(val value: Int)<br>@JvmInline<br>value class OrderId(val value: Int)<br><br>fun processOrder(userId: UserId, productId: ProductId, orderId: OrderId) {<br>    println(&quot;Processing order ${orderId.value} for user ${userId.value}&quot;)<br>}</pre><p>At compile time, this looks exactly like the regular class version. You get type safety — the compiler will yell if you mix up the parameters.</p><p>But at runtime? The Kotlin compiler is smart. It sees these value classes and thinks “I can optimize this away.” Your UserId(123) becomes just 123 in the final bytecode.</p><h3>Real Example: Money Handling</h3><p>Let me show you a practical example. I was building a payment system and needed to handle different currencies:</p><pre>@JvmInline<br>value class USD(val cents: Int)<br>@JvmInline  <br>value class EUR(val cents: Int)<br>@JvmInline<br>value class GBP(val pence: Int)<br><br>fun chargeCreditCard(amount: USD) {<br>    println(&quot;Charging ${amount.cents} cents USD&quot;)<br>}<br>fun convertToEur(usd: USD): EUR {<br>    // Pretend exchange rate logic here  <br>    return EUR((usd.cents * 0.85).toInt())<br>}</pre><p>Without value classes, I might have written:</p><pre>fun chargeCreditCard(amountInCents: Int, currency: String) {<br>    // Hope nobody passes the wrong currency string!<br>    println(&quot;Charging $amountInCents cents $currency&quot;)<br>}</pre><p>But that’s dangerous. Someone could easily pass euros where dollars are expected, or misspell “USD” as “usd”.</p><p>With value classes, this becomes impossible:</p><pre>val payment = USD(1500) // $15.00<br>chargeCreditCard(payment)<br><br>val euroAmount = EUR(1200) <br>// chargeCreditCard(euroAmount) // Won&#39;t compile!</pre><h3>How Kotlin Handles This Internally</h3><p>Here’s what’s happening under the hood. When you write:</p><pre>@JvmInline<br>value class UserId(val value: Int)<br><br>fun getUser(id: UserId): String {<br>    return &quot;User with ID: ${id.value}&quot;<br>}<br>val user = getUser(UserId(42))</pre><p>The Kotlin compiler transforms this into something like:</p><pre>// What the JVM actually sees:<br>fun getUser(id: Int): String {  // UserId disappeared!<br>    return &quot;User with ID: $id&quot;<br>}<br><br>val user = getUser(42)  // No object creation!</pre><p>The value class completely vanishes at runtime. You get the same performance as if you’d used raw integers, but with compile-time safety.</p><p>There are some cases where Kotlin can’t value the class, like when you use it as a generic type parameter or store it in a collection. In those cases, it falls back to creating real objects. But for most everyday use, it’s optimised away.</p><h3>More Practical Examples</h3><h3>API Tokens</h3><pre>@JvmInline  <br>value class ApiToken(val value: String)<br><br>@JvmInline<br>value class RefreshToken(val value: String)<br><br>fun authenticateRequest(token: ApiToken): Boolean {<br>    // Can&#39;t accidentally pass a refresh token here<br>    return token.value.startsWith(&quot;api_&quot;)<br>}</pre><h3>Database IDs</h3><pre>@JvmInline<br>value class CustomerId(val id: Long)<br><br>@JvmInline  <br>value class InvoiceId(val id: Long)<br><br>fun findInvoicesForCustomer(customerId: CustomerId): List&lt;InvoiceId&gt; {<br>    // Type-safe database queries<br>    return database.query(&quot;SELECT id FROM invoices WHERE customer_id = ?&quot;, customerId.id)<br>        .map { InvoiceId(it.getLong(&quot;id&quot;)) }<br>}</pre><h3>Units of Measurement</h3><pre>@JvmInline<br>value class Meters(val value: Double)<br><br>@JvmInline<br>value class Feet(val value: Double)  <br><br>fun calculateArea(length: Meters, width: Meters): Meters {<br>    return Meters(length.value * width.value)<br>}<br>// Can&#39;t mix feet and meters by accident<br>val roomLength = Meters(5.0)<br>val roomWidth = Meters(3.0) <br>val area = calculateArea(roomLength, roomWidth)</pre><h3>When NOT to Use Value Classes</h3><p>They’re not perfect for everything. Here are cases where I don’t use them:</p><p><strong>Multiple properties</strong>: Value classes can only wrap a SINGLE value. You literally can’t do this:</p><pre>// This won&#39;t even compile!<br>@JvmInline<br>value class User(val id: Int, val name: String, val email: String) // ERROR!</pre><p>But you SHOULD use value classes for the individual parts:</p><pre>@JvmInline<br>value class UserId(val value: Int)<br><br>@JvmInline  <br>value class UserName(val value: String)<br><br>@JvmInline<br>value class Email(val value: String)<br><br>// Then use them in your regular class<br>data class User(<br>    val id: UserId, <br>    val name: UserName, <br>    val email: Email<br>) {<br>    fun sendEmail() { /* complex logic */ }<br>    fun validateData() { /* more logic */ }<br>}</pre><p>This way, you get type safety for each individual field, but you can still have a regular class with multiple properties and methods.</p><p><strong>Collections of them</strong>: When you put value classes in lists or maps, they often can’t be valued anymore.</p><p><strong>Inheritance</strong>: Value classes can’t extend other classes or be extended.</p><h3>The Bottom Line</h3><p>Value classes solve a real problem: they let you write safer code without sacrificing performance. They’re especially useful for:</p><ul><li>Wrapping primitive types (IDs, tokens, measurements)</li><li>Preventing parameter mix-ups</li><li>Making APIs harder to misuse</li><li>Adding meaning to simple values</li></ul><p>I’ve started using them everywhere I used to create simple wrapper classes. My code is safer, and the performance is identical to using raw primitives.</p><p>Try them out in your next project. Once you start using value classes, you’ll wonder how you lived without them.</p><p>For any questions or queries, let’s connect on LinkedIn</p><p><a href="https://www.linkedin.com/in/devbaljeet/">https://www.linkedin.com/in/devbaljeet/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ee2626afb0d" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/kotlin-value-classes-stop-wrapping-everything-in-regular-classes-2ee2626afb0d">Kotlin Value Classes: Stop Wrapping Everything in Regular Classes</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type-safe Builders in Kotlin: Stop Making Those Silly Mistakes]]></title>
            <link>https://proandroiddev.com/type-safe-builders-in-kotlin-stop-making-those-silly-mistakes-e267c2cfa98a?source=rss-ee347576cb25------2</link>
            <guid isPermaLink="false">https://medium.com/p/e267c2cfa98a</guid>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-apps]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Baljeet Singh]]></dc:creator>
            <pubDate>Sun, 28 Sep 2025 14:19:59 GMT</pubDate>
            <atom:updated>2025-09-28T14:19:59.874Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PiMmfccuPqKJ8RoCwRbkrA.jpeg" /></figure><p>I used to hate building complex objects in my Android code. You know the drill — you create an object, set a bunch of properties, forget to set one important field, and boom! Your app crashes in production.</p><p>Last month, I spent three hours debugging why our payment system was failing. Turns out I forgot to set the currency field when building a payment request. The object looked complete, but it wasn’t. That’s when I decided to finally learn about Kotlin’s type-safe builders.</p><h3>What Are Type-safe Builders Anyway?</h3><p>Think of a type-safe builder like a checklist that the compiler checks for you. Instead of creating objects and hoping you didn’t miss anything, the builder pattern forces you to provide all the required information before you can build the object.</p><p>Here’s a simple example. Let’s say we’re building a User object:</p><pre>// The old way (error-prone)<br>val user = User(<br>    name = &quot;John&quot;,<br>    email = &quot;john@example.com&quot;<br>    // Oops, forgot the age!<br>)<br><br>// The builder way (type-safe)<br>val user = user {<br>    name = &quot;John&quot;<br>    email = &quot;john@example.com&quot; <br>    age = 25<br>} // This won&#39;t compile if we miss anything!</pre><h3>Building Our First Type-safe Builder</h3><p>Let me show you how I built a simple builder for our email system. We send a lot of emails, and I was tired of missing required fields.</p><pre>data class Email(<br>    val to: String,<br>    val subject: String,<br>    val body: String,<br>    val from: String? = null<br>)<br><br>class EmailBuilder {<br>    var to: String? = null<br>    var subject: String? = null<br>    var body: String? = null<br>    var from: String? = null<br>    <br>    fun build(): Email {<br>        return Email(<br>            to = to ?: throw IllegalStateException(&quot;Email &#39;to&#39; is required&quot;),<br>            subject = subject ?: throw IllegalStateException(&quot;Email &#39;subject&#39; is required&quot;),<br>            body = body ?: throw IllegalStateException(&quot;Email &#39;body&#39; is required&quot;),<br>            from = from<br>        )<br>    }<br>}<br>fun email(block: EmailBuilder.() -&gt; Unit): Email {<br>    return EmailBuilder().apply(block).build()<br>}</pre><p>Now I can build emails like this:</p><pre>val welcomeEmail = email {<br>    to = &quot;newuser@example.com&quot;<br>    subject = &quot;Welcome to our app!&quot;<br>    body = &quot;Thanks for joining us!&quot;<br>    from = &quot;noreply@ourapp.com&quot;<br>}</pre><p>This is better, but it still has a problem. The compiler doesn’t stop me from calling the builder before setting all required fields. Let’s fix that.</p><h3>Making It Actually Type-safe</h3><p>Here’s where Kotlin’s DSL magic happens. We can use sealed interfaces to track which fields have been set:</p><pre>sealed interface EmailBuilderState<br>object EmptyEmailBuilder : EmailBuilderState<br>sealed interface WithTo : EmailBuilderState<br>sealed interface WithSubject : EmailBuilderState  <br>sealed interface WithBody : EmailBuilderState<br><br>class TypeSafeEmailBuilder&lt;T : EmailBuilderState&gt; {<br>    internal var to: String? = null<br>    internal var subject: String? = null<br>    internal var body: String? = null<br>    internal var from: String? = null<br>    <br>    fun to(email: String): TypeSafeEmailBuilder&lt;WithTo&gt; {<br>        this.to = email<br>        return this as TypeSafeEmailBuilder&lt;WithTo&gt;<br>    }<br>    <br>    fun subject(text: String): TypeSafeEmailBuilder&lt;T&gt; where T : WithTo {<br>        this.subject = text<br>        return this as TypeSafeEmailBuilder&lt;WithSubject&gt;<br>    }<br>    <br>    fun body(text: String): TypeSafeEmailBuilder&lt;T&gt; where T : WithTo, T : WithSubject {<br>        this.body = text<br>        return this as TypeSafeEmailBuilder&lt;WithBody&gt;<br>    }<br>    <br>    fun from(email: String): TypeSafeEmailBuilder&lt;T&gt; {<br>        this.from = email<br>        return this<br>    }<br>}<br>fun TypeSafeEmailBuilder&lt;WithBody&gt;.build(): Email {<br>    return Email(to!!, subject!!, body!!, from)<br>}<br>fun email(block: TypeSafeEmailBuilder&lt;EmptyEmailBuilder&gt;.() -&gt; TypeSafeEmailBuilder&lt;WithBody&gt;): Email {<br>    return TypeSafeEmailBuilder&lt;EmptyEmailBuilder&gt;().block().build()<br>}</pre><p>Now Kotlin won’t let me build an incomplete email:</p><pre>// This won&#39;t compile!<br>val incomplete = email {<br>    to(&quot;user@example.com&quot;)<br>    // Missing subject and body<br>}<br><br>// This works<br>val complete = email {<br>    to(&quot;user@example.com&quot;)<br>        .subject(&quot;Hello&quot;)<br>        .body(&quot;World&quot;)<br>}</pre><h3>A Simpler Approach with @DslMarker</h3><p>Actually, let me show you a much simpler way that I use in real projects. Kotlin’s @DslMarker makes building DSLs super easy:</p><pre>@DslMarker<br>annotation class EmailDsl<br><br>data class Email(<br>    val to: String,<br>    val subject: String,<br>    val body: String,<br>    val from: String? = null,<br>    val cc: List&lt;String&gt; = emptyList(),<br>    val bcc: List&lt;String&gt; = emptyList()<br>)<br>@EmailDsl<br>class EmailBuilder {<br>    lateinit var to: String<br>    lateinit var subject: String  <br>    lateinit var body: String<br>    var from: String? = null<br>    private val ccList = mutableListOf&lt;String&gt;()<br>    private val bccList = mutableListOf&lt;String&gt;()<br>    <br>    fun cc(vararg emails: String) {<br>        ccList.addAll(emails)<br>    }<br>    <br>    fun bcc(vararg emails: String) {<br>        bccList.addAll(emails)<br>    }<br>    <br>    internal fun build(): Email {<br>        check(::to.isInitialized) { &quot;Email &#39;to&#39; must be set&quot; }<br>        check(::subject.isInitialized) { &quot;Email &#39;subject&#39; must be set&quot; }<br>        check(::body.isInitialized) { &quot;Email &#39;body&#39; must be set&quot; }<br>        <br>        return Email(to, subject, body, from, ccList, bccList)<br>    }<br>}<br>fun email(block: EmailBuilder.() -&gt; Unit): Email {<br>    return EmailBuilder().apply(block).build()<br>}</pre><p>Usage is clean and readable:</p><pre>val email = email {<br>    to = &quot;user@example.com&quot;<br>    subject = &quot;Welcome!&quot;<br>    body = &quot;Thanks for joining us.&quot;<br>    from = &quot;noreply@app.com&quot;<br>    cc(&quot;manager@app.com&quot;, &quot;support@app.com&quot;)<br>    bcc(&quot;analytics@app.com&quot;)<br>}</pre><h3>Real-world Example: Building HTTP Requests</h3><p>At my job, we use builders for creating HTTP requests. Here’s how I built one with Retrofit:</p><pre>@DslMarker<br>annotation class HttpDsl<br><br>data class ApiRequest(<br>    val url: String,<br>    val method: String,<br>    val headers: Map&lt;String, String&gt;,<br>    val queryParams: Map&lt;String, String&gt;,<br>    val body: String?<br>)<br>@HttpDsl<br>class RequestBuilder {<br>    lateinit var url: String<br>    var method: String = &quot;GET&quot;<br>    private val headerMap = mutableMapOf&lt;String, String&gt;()<br>    private val queryMap = mutableMapOf&lt;String, String&gt;()<br>    var body: String? = null<br>    <br>    @HttpDsl<br>    class HeadersBuilder {<br>        internal val headers = mutableMapOf&lt;String, String&gt;()<br>        <br>        operator fun String.invoke(value: String) {<br>            headers[this] = value<br>        }<br>    }<br>    <br>    @HttpDsl  <br>    class QueryBuilder {<br>        internal val params = mutableMapOf&lt;String, String&gt;()<br>        <br>        operator fun String.invoke(value: String) {<br>            params[this] = value<br>        }<br>    }<br>    <br>    fun headers(block: HeadersBuilder.() -&gt; Unit) {<br>        val builder = HeadersBuilder().apply(block)<br>        headerMap.putAll(builder.headers)<br>    }<br>    <br>    fun query(block: QueryBuilder.() -&gt; Unit) {<br>        val builder = QueryBuilder().apply(block) <br>        queryMap.putAll(builder.params)<br>    }<br>    <br>    fun post(bodyContent: String) {<br>        method = &quot;POST&quot;<br>        body = bodyContent<br>    }<br>    <br>    internal fun build(): ApiRequest {<br>        check(::url.isInitialized) { &quot;URL must be set&quot; }<br>        return ApiRequest(url, method, headerMap, queryMap, body)<br>    }<br>}<br>fun request(block: RequestBuilder.() -&gt; Unit): ApiRequest {<br>    return RequestBuilder().apply(block).build()<br>}</pre><p>Now I can build requests like this:</p><pre>val apiRequest = request {<br>    url = &quot;https://api.example.com/users&quot;<br>    <br>    headers {<br>        &quot;Authorization&quot;(&quot;Bearer $token&quot;)<br>        &quot;Content-Type&quot;(&quot;application/json&quot;)<br>    }<br>    <br>    query {<br>        &quot;page&quot;(&quot;1&quot;)<br>        &quot;limit&quot;(&quot;20&quot;)<br>    }<br>    <br>    post(&quot;&quot;&quot;{<br>        &quot;name&quot;: &quot;John Doe&quot;,<br>        &quot;email&quot;: &quot;john@example.com&quot;<br>    }&quot;&quot;&quot;)<br>}</pre><h3>Building HTML with Type-safe DSL</h3><p>One of my favorite Kotlin features is building HTML with kotlinx.html. Here’s how you can create your own simple HTML DSL:</p><pre>@DslMarker<br>annotation class HtmlDsl<br><br>abstract class Element(private val name: String) {<br>    private val children = mutableListOf&lt;Element&gt;()<br>    private val attributes = mutableMapOf&lt;String, String&gt;()<br>    <br>    protected fun &lt;T : Element&gt; initTag(tag: T, init: T.() -&gt; Unit): T {<br>        tag.init()<br>        children.add(tag)<br>        return tag<br>    }<br>    <br>    fun attribute(name: String, value: String) {<br>        attributes[name] = value<br>    }<br>    <br>    override fun toString(): String {<br>        val attrs = attributes.entries.joinToString(&quot; &quot;) { &quot;${it.key}=\&quot;${it.value}\&quot;&quot; }<br>        val attrsStr = if (attrs.isNotEmpty()) &quot; $attrs&quot; else &quot;&quot;<br>        val childrenStr = children.joinToString(&quot;&quot;)<br>        return &quot;&lt;$name$attrsStr&gt;$childrenStr&lt;/$name&gt;&quot;<br>    }<br>}<br>@HtmlDsl<br>class HTML : Element(&quot;html&quot;) {<br>    fun head(init: Head.() -&gt; Unit) = initTag(Head(), init)<br>    fun body(init: Body.() -&gt; Unit) = initTag(Body(), init)<br>}<br>@HtmlDsl  <br>class Head : Element(&quot;head&quot;) {<br>    fun title(init: Title.() -&gt; Unit) = initTag(Title(), init)<br>}<br>@HtmlDsl<br>class Title : Element(&quot;title&quot;) {<br>    operator fun String.unaryPlus() {<br>        // Add text content<br>    }<br>}<br>@HtmlDsl<br>class Body : Element(&quot;body&quot;) {<br>    fun div(init: Div.() -&gt; Unit) = initTag(Div(), init)<br>    fun p(init: P.() -&gt; Unit) = initTag(P(), init)<br>}<br>@HtmlDsl<br>class Div : Element(&quot;div&quot;) {<br>    fun p(init: P.() -&gt; Unit) = initTag(P(), init)<br>}<br>@HtmlDsl<br>class P : Element(&quot;p&quot;)<br>fun html(init: HTML.() -&gt; Unit): HTML {<br>    return HTML().apply(init)<br>}</pre><p>Usage:</p><pre>val page = html {<br>    head {<br>        title { +&quot;My Page&quot; }<br>    }<br>    body {<br>        div {<br>            attribute(&quot;class&quot;, &quot;container&quot;)<br>            p { +&quot;Hello World!&quot; }<br>        }<br>    }<br>}</pre><h3>When Should You Use Type-safe Builders?</h3><p>I don’t use builders for everything. Here’s when they make sense:</p><p><strong>Use builders when:</strong></p><ul><li>You have objects with many required fields</li><li>You’re building complex configurations</li><li>You want to prevent runtime errors from missing fields</li><li>You need a clean, readable DSL for your API</li></ul><p><strong>Don’t use builders when:</strong></p><ul><li>You have simple data classes with just a few fields</li><li>All fields have reasonable defaults</li><li>You’re building one-off objects that won’t be reused</li></ul><h3>Making Builders Easier with Delegation</h3><p>Kotlin’s property delegation can make builders even cleaner:</p><pre>class RequiredProperty&lt;T&gt; : ReadWriteProperty&lt;Any?, T&gt; {<br>    private var value: T? = null<br>    private var isSet = false<br>    <br>    override fun getValue(thisRef: Any?, property: KProperty&lt;*&gt;): T {<br>        if (!isSet) throw IllegalStateException(&quot;Property ${property.name} must be set&quot;)<br>        return value!!<br>    }<br>    <br>    override fun setValue(thisRef: Any?, property: KProperty&lt;*&gt;, value: T) {<br>        this.value = value<br>        isSet = true<br>    }<br>}<br>fun &lt;T&gt; required(): ReadWriteProperty&lt;Any?, T&gt; = RequiredProperty()<br>class UserBuilder {<br>    var name: String by required()<br>    var email: String by required()  <br>    var age: Int by required()<br>    var city: String? = null<br>    <br>    fun build() = User(name, email, age, city)<br>}<br>fun user(block: UserBuilder.() -&gt; Unit): User {<br>    return UserBuilder().apply(block).build()<br>}</pre><p>Now building objects is super clean:</p><pre>val user = user {<br>    name = &quot;Alice&quot;<br>    email = &quot;alice@example.com&quot;<br>    age = 30<br>    city = &quot;New York&quot;<br>}</pre><h3>The Bottom Line</h3><p>Type-safe builders in Kotlin saved me hours of debugging time. Yes, they require more upfront work, but they catch errors at compile time instead of runtime.</p><p>The @DslMarker annotation and apply function make building DSLs in Kotlin really enjoyable. You can create APIs that feel like they&#39;re part of the language itself.</p><p>Start small. Pick one complex object in your Android app and try building a type-safe builder for it. I bet you’ll find at least one place where you were missing a required field without realizing it.</p><p>Kotlin’s builders are especially powerful for configuration objects, test data setup, and anywhere you need a clean, readable API.</p><p><em>Have you used type-safe builders in your Kotlin projects? What patterns have worked well for you? I’d love to hear about your experiences.</em></p><p>For any questions or queries, let’s connect on LinkedIn</p><p><a href="https://www.linkedin.com/in/devbaljeet/">https://www.linkedin.com/in/devbaljeet/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e267c2cfa98a" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/type-safe-builders-in-kotlin-stop-making-those-silly-mistakes-e267c2cfa98a">Type-safe Builders in Kotlin: Stop Making Those Silly Mistakes</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Delegates: From Java to Kotlin Made Simple]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://ibaljeet.medium.com/understanding-delegates-from-java-to-kotlin-made-simple-b466401f4ed4?source=rss-ee347576cb25------2"><img src="https://cdn-images-1.medium.com/max/2600/1*FRWBVwOHPYFDIVTp_ylZNQ.jpeg" width="3543"></a></p><p class="medium-feed-snippet">Ever felt confused about delegates? You&#x2019;re not alone. I spent weeks trying to wrap my head around this concept when I first encountered it&#x2026;</p><p class="medium-feed-link"><a href="https://ibaljeet.medium.com/understanding-delegates-from-java-to-kotlin-made-simple-b466401f4ed4?source=rss-ee347576cb25------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://ibaljeet.medium.com/understanding-delegates-from-java-to-kotlin-made-simple-b466401f4ed4?source=rss-ee347576cb25------2</link>
            <guid isPermaLink="false">https://medium.com/p/b466401f4ed4</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-apps]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Baljeet Singh]]></dc:creator>
            <pubDate>Tue, 23 Sep 2025 14:34:41 GMT</pubDate>
            <atom:updated>2025-09-23T14:34:41.438Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Kotlin Infix Functions: The Secret to Natural Language Code]]></title>
            <link>https://proandroiddev.com/kotlin-infix-functions-the-secret-to-natural-language-code-1fb370e7f221?source=rss-ee347576cb25------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fb370e7f221</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-apps]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[Baljeet Singh]]></dc:creator>
            <pubDate>Sun, 21 Sep 2025 16:06:08 GMT</pubDate>
            <atom:updated>2025-09-21T16:06:08.689Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*kWhTLhavayixUlvlX6S9fA.png" /></figure><p>I remember the first time I saw this line of Kotlin code:</p><pre>val coordinates = 10 to 20</pre><p>Coming from Java, I thought “to” was some special keyword. Turns out, it’s just a regular function call! This is the magic of <strong>infix functions</strong> — one of Kotlin’s most elegant features that makes code read like natural language.</p><p>Today, I want to share everything I’ve learned about infix functions, including how they work under the hood and how you can create powerful, readable APIs with them.</p><h3>What Are Infix Functions?</h3><p>Infix functions allow some functions to be called without using the period and brackets. Instead of writing object.method(parameter), you can write object method parameter. It&#39;s syntactic sugar that makes your code more readable and expressive.</p><p>Here’s how a normal function call looks vs an infix call:</p><pre>// Normal function call<br>val pair1 = &quot;key&quot;.to(&quot;value&quot;)<br><br>// Infix function call<br>val pair2 = &quot;key&quot; to &quot;value&quot;</pre><p>Both do exactly the same thing, but the infix version reads more naturally.</p><h3>The Rules: What Makes a Function “Infix-able”?</h3><p>For a function to work as an infix function, it must follow three simple rules:</p><ol><li><strong>It must be a member function or an extension function</strong></li><li><strong>It must have exactly one parameter</strong></li><li><strong>It must be marked with the </strong><strong>infix keyword</strong></li></ol><p>That’s it! Let me show you with examples:</p><pre>// Member function<br>class Calculator(val value: Int) {<br>    infix fun add(value: Int): Int {<br>        return this.value + value<br>    }<br>}<br><br>// Extension function<br>infix fun Int.powerOf(exponent: Int): Double {<br>    return this.toDouble().pow(exponent)<br>}<br><br>fun main() {<br>    // Usage<br>    val calc = Calculator(5)<br>    val result1 = calc add 10  // Member function<br>    val result2 = 2 powerOf 3  // Extension function (result: 8.0)<br>}</pre><h3>Range Operators: Infix Functions You Use Every Day</h3><p>Remember those range operators I mentioned at the start? rangeTo, downTo, until, step - they&#39;re all infix functions! Let me show you what&#39;s really happening:</p><h3>The .. operator (rangeTo)</h3><pre>// What you write<br>for (i in 1..5) { /* ... */ }<br><br>// What actually happens<br>for (i in 1.rangeTo(5)) { /* ... */ }</pre><p>The rangeTo function is defined as an infix function in the Int class.</p><h3>The downTo operator</h3><pre>// Infix style<br>for (i in 10 downTo 1) { /* ... */ }<br><br>// Regular function call equivalent<br>for (i in 10.downTo(1)) { /* ... */ }</pre><h3>The until operator</h3><pre>// Infix style<br>for (i in 0 until 10) { /* ... */ }<br><br>// Regular function call<br>for (i in 0.until(10)) { /* ... */ }</pre><h3>The step function</h3><pre>// Infix chaining<br>for (i in 1..10 step 2) { /* ... */ }<br><br>// What actually happens<br>for (i in (1..10).step(2)) { /* ... */ }</pre><p>Pretty cool, right? These operators that feel built into the language are just regular functions using infix notation!</p><h3>How Infix Functions Work Under the Hood</h3><p>When Kotlin compiles to Java bytecode, infix functions are converted to regular method calls. Here’s what happens:</p><pre>// Kotlin infix call<br>val result = 5 add 3<br><br>// Compiles to something like this Java code:<br>// int result = calculator.add(3);</pre><p>The Kotlin compiler automatically transforms the infix syntax into standard method calls. There’s no runtime overhead — it’s purely a compile-time transformation.</p><p>Let me show you with a practical example:</p><pre>class MathOperations(private val value: Int) {<br>    infix fun plus(other: Int) = MathOperations(value + other)<br>    infix fun times(other: Int) = MathOperations(value * other)<br><br>    override fun toString() = value.toString()<br>}<br><br>fun main() {<br>    val math = MathOperations(5)<br>    val result = math plus 3 times 2<br>}</pre><p>This gets compiled to regular Java method calls behind the scenes, maintaining all the performance of normal function calls.</p><h3>Real-World Use Cases: Where Infix Functions Shine</h3><h3>1. Domain-Specific Languages (DSLs)</h3><p>Infix functions are perfect for creating readable DSLs. Here’s a simple test framework:</p><pre>class TestAssertion&lt;T&gt;(private val actual: T) {<br>    infix fun shouldBe(expected: T) {<br>        if (actual != expected) {<br>            throw AssertionError(&quot;Expected $expected but was $actual&quot;)<br>        }<br>    }<br><br>    infix fun shouldNotBe(expected: T) {<br>        if (actual == expected) {<br>            throw AssertionError(&quot;Expected not to be $expected&quot;)<br>        }<br>    }<br>}<br><br>infix fun &lt;T&gt; T.should(assertion: TestAssertion&lt;T&gt;.() -&gt; Unit) {<br>    TestAssertion(this).assertion()<br>}<br><br>fun main() {<br>    // Usage - reads like natural language!<br>    val name = TestAssertion(&quot;John&quot;)<br>    name shouldBe &quot;John&quot;<br>    name shouldNotBe &quot;Jane&quot;<br>    val age = TestAssertion(25)<br>    age shouldBe 25<br><br>    &quot;john&quot; should {<br>        shouldBe(&quot;john&quot;)<br>        shouldNotBe(&quot;doe&quot;)<br>    }<br><br>    10 should {<br>        shouldBe(10)<br>        shouldNotBe(5)<br>    }<br>}</pre><h3>2. Configuration and Setup</h3><pre>class DatabaseConfig {<br>    var host: String = &quot;&quot;<br>    var port: Int = 0<br>    var database: String = &quot;&quot;<br>}<br><br>infix fun DatabaseConfig.host(value: String) = apply { host = value }<br>infix fun DatabaseConfig.port(value: Int) = apply { port = value }<br>infix fun DatabaseConfig.database(value: String) = apply { database = value }<br><br>fun main() {<br>    // Usage<br>    val config = DatabaseConfig()<br>        .host(&quot;localhost&quot;)<br>        .port(5432)<br>        .database(&quot;myapp&quot;)<br>    // Or even more natural:<br>    fun configureDatabase() = DatabaseConfig().apply {<br>        this host &quot;localhost&quot;<br>        this port 5432<br>        this database &quot;myapp&quot;<br>    }<br>}</pre><h3>3. Time and Duration APIs</h3><pre>data class Duration(val amount: Long, val unit: TimeUnit)<br><br>infix fun Int.seconds(unit: String): Duration = Duration(this.toLong(), TimeUnit.SECONDS)<br>infix fun Int.minutes(unit: String): Duration = Duration(this.toLong(), TimeUnit.MINUTES)<br>infix fun Int.hours(unit: String): Duration = Duration(this.toLong(), TimeUnit.HOURS)<br><br>fun main() {<br>// Usage<br>    val timeout = 30 seconds &quot;timeout&quot;<br>    val cacheExpiry = 5 minutes &quot;cache&quot;<br>    val sessionDuration = 2 hours &quot;session&quot;<br>}</pre><h3>4. Mathematical Operations</h3><pre>data class Vector2D(val x: Double, val y: Double) {<br>    infix fun dot(other: Vector2D): Double = x * other.x + y * other.y<br>    infix fun cross(other: Vector2D): Double = x * other.y - y * other.x<br>}<br><br>fun main() {<br>    // Usage<br>    val v1 = Vector2D(3.0, 4.0)<br>    val v2 = Vector2D(1.0, 2.0)<br>    val dotProduct = v1 dot v2      // 11.0<br>    val crossProduct = v1 cross v2  // 2.0<br>}</pre><h3>5. String Matching and Validation</h3><pre>infix fun String.matches(pattern: String): Boolean = this.matches(pattern.toRegex())<br>infix fun String.contains(substring: String): Boolean = this.contains(substring, ignoreCase = true)<br>infix fun String.startsWith(prefix: String): Boolean = this.startsWith(prefix, ignoreCase = true)<br><br>// Usage in validation<br>fun validateEmail(email: String): Boolean {<br>    return email matches &quot;^[A-Za-z0-9+_.-]+@([A-Za-z0-9.-]+\\.[A-Za-z]{2,})$&quot;<br>            &amp;&amp; email contains &quot;@&quot;<br>            &amp;&amp; !(email startsWith &quot;@&quot;)<br>}</pre><h3>Creating Your Own Infix Function Library</h3><p>Let’s build a practical example — a fluent assertion library for testing:</p><pre>class Expect&lt;T&gt;(val actual: T) {<br>    infix fun toBe(expected: T) = apply {<br>        if (actual != expected) {<br>            throw AssertionError(&quot;Expected &#39;$expected&#39; but was &#39;$actual&#39;&quot;)<br>        }<br>    }<br><br>    infix fun &lt;T : Comparable&lt;T&gt;&gt; Expect&lt;T&gt;.toBeGreaterThan(expected: T) = apply {<br>        if (actual &lt;= expected) {<br>            throw AssertionError(&quot;Expected &#39;$actual&#39; to be greater than &#39;$expected&#39;&quot;)<br>        }<br>    }<br><br>    infix fun toContain(element: Any) = apply {<br>        if (actual is Collection&lt;*&gt; &amp;&amp; element !in actual) {<br>            throw AssertionError(&quot;Expected $actual to contain $element&quot;)<br>        }<br>    }<br>}<br><br>infix fun &lt;T&gt; T.should(block: Expect&lt;T&gt;.() -&gt; Unit) {<br>    Expect(this).apply(block)<br>}<br><br>fun main() {// Usage<br>    val numbers = listOf(1, 2, 3, 4, 5)<br>    numbers should {<br>        toContain(3)<br>    }<br>    val name = &quot;John Doe&quot;<br>    name should {<br>        toBe(&quot;John Doe&quot;)<br>    }<br>    val age = 25<br>    age should {<br>        toBeGreaterThan(18)<br>    }<br>}</pre><h3>Performance Considerations</h3><p>One thing I love about infix functions is that they have zero runtime cost. The Kotlin compiler transforms them into regular method calls, so there’s no performance penalty. The presence of the infix keyword allows us to write code that is cleaner to read and easier to understand without sacrificing performance.</p><p>Here’s what the compiler does:</p><pre>// Your infix code<br>val result = calculator add 5<br><br>// Compiler generates (simplified):<br>val result = calculator.add(5)</pre><h3>Best Practices for Infix Functions</h3><h3>1. Use Them Sparingly</h3><p>Not every function should be infix. Save it for cases where it genuinely improves readability:</p><pre>// Good - reads naturally<br>user hasPermission &quot;ADMIN&quot;<br><br>// Bad - doesn&#39;t improve readability<br>list add element  // prefer list.add(element)</pre><h3>2. Make Operations Feel Natural</h3><p>The best infix functions read like English:</p><pre>// Natural<br>file writeTo directory<br>user belongsTo group<br>config overriddenBy userPrefs<br><br>// Unnatural<br>config.serialize() // this shouldn&#39;t be infix</pre><h3>3. Consider Chaining</h3><p>Infix functions can be chained, but use this carefully:</p><pre>// OK for mathematical operations<br>val result = vector add otherVector scale 2.0<br><br>// Can become hard to read<br>val user = User() hasName &quot;John&quot; hasAge 25 belongsTo adminGroup</pre><h3>Common Pitfalls to Avoid</h3><h3>1. Operator Precedence Confusion</h3><pre>// This might not do what you expect<br>val result = 2 + 3 multiply 4  // Actually: 2 + (3 multiply 4)<br><br>// Be explicit with parentheses when mixing operators<br>val result = (2 + 3) multiply 4</pre><h3>2. Not Considering Java Interop</h3><p>If your Kotlin code needs to be called from Java, remember that Java users will need to use the regular method syntax:</p><pre>// Kotlin<br>val pair = &quot;key&quot; to &quot;value&quot;<br><br>// Java (this won&#39;t work in Java)<br>// Pair&lt;String, String&gt; pair = &quot;key&quot; to &quot;value&quot;;  // Compile error<br>// Java (correct way)<br>Pair&lt;String, String&gt; pair = TuplesKt.to(&quot;key&quot;, &quot;value&quot;);</pre><h3>Wrapping Up</h3><p>Infix functions are one of those Kotlin features that seem simple on the surface but open up powerful possibilities for creating readable, expressive code. They can result in code that looks much more like a natural language, making your APIs more intuitive and your code more maintainable.</p><p>The range operators we use every day (.., downTo, until, step) are perfect examples of how infix functions can make everyday programming tasks feel more natural. And when you need to create domain-specific languages or fluent APIs, infix functions become an indispensable tool.</p><p>Remember the three rules: member or extension function, exactly one parameter, and the infix keyword. Follow these, use them judiciously, and you&#39;ll find yourself writing code that not only works well but reads beautifully too.</p><p>Next time you’re designing an API or writing a utility function, ask yourself: “Would this read better as an infix function?” You might be surprised how often the answer is yes.</p><p>For any questions or queries, let’s connect on LinkedIn</p><p><a href="https://www.linkedin.com/in/devbaljeet/">https://www.linkedin.com/in/devbaljeet/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fb370e7f221" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/kotlin-infix-functions-the-secret-to-natural-language-code-1fb370e7f221">Kotlin Infix Functions: The Secret to Natural Language Code</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Golden Rule of Coroutine Exceptions]]></title>
            <link>https://proandroiddev.com/the-golden-rule-of-coroutine-exceptions-8d4538158ab5?source=rss-ee347576cb25------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d4538158ab5</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-apps]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[Baljeet Singh]]></dc:creator>
            <pubDate>Sun, 21 Sep 2025 16:00:53 GMT</pubDate>
            <atom:updated>2025-09-21T16:00:53.454Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zdYS5IjjVEhx0Q1XGstNyg.jpeg" /><figcaption>Designed by catalyststuff on Freepik</figcaption></figure><p>At its heart, exception handling in coroutines is all about <strong>structured concurrency</strong>. Think of it like a family tree. If a child coroutine fails with an exception, it tells its parent. The parent then cancels all its other children and then cancels itself, passing the exception further up the tree. This ensures no coroutine is ever lost or orphaned.</p><p>Let’s dive into the different scenarios you’ll encounter.</p><h3>Case 1: The launch Builder</h3><p>launch is your &quot;fire-and-forget&quot; coroutine builder. You use it when you don&#39;t need a result back. Its exception behaviour can be a bit tricky at first.</p><h4>Incorrect: try-catch outside launch</h4><p>This is a common mistake. Wrapping a launch call in a try-catch block <strong>will not</strong> catch exceptions that happen inside it.</p><ul><li><strong>Why?</strong>: The launch function returns immediately, and the code inside it runs on a different thread in the background. The try-catch block finishes long before the exception even happens. The exception propagates up to the top-level handler, and your app will crash if it&#39;s not handled.</li></ul><p><strong>Example</strong></p><pre>import kotlinx.coroutines.*<br><br>fun main() = runBlocking {<br>    println(&quot;Before launch&quot;)<br>    try {<br>        // This launch block will throw an exception<br>        launch {<br>            println(&quot;Inside launch: Throwing exception...&quot;)<br>            delay(500) // Simulate some work<br>            throw RuntimeException(&quot;Something went wrong!&quot;)<br>        }<br>    } catch (e: Exception) {<br>        // ❌ THIS BLOCK WILL NEVER BE REACHED ❌<br>        println(&quot;Caught exception: $e&quot;)<br>    }<br>    println(&quot;After launch&quot;)<br>    delay(1000) // Keep the main coroutine alive to see the crash<br>    println(&quot;Main finished&quot;)<br>}</pre><p><strong>Output:</strong></p><pre>Before launch<br>After launch<br>Inside launch: Throwing exception...<br>Exception in thread &quot;main&quot; java.lang.RuntimeException: Something went wrong!<br>... (stack trace) ...</pre><p>Notice how “Caught exception” is never printed. The app just crashes.</p><h4>Correct: try-catch inside launch</h4><p>To handle an exception specific to a launch coroutine, place the try-catch block directly inside its lambda.</p><ul><li><strong>Why?</strong>: This puts the exception handling logic right where the exception occurs, within the coroutine’s own execution path. This way, you can gracefully handle the error without crashing the entire scope.</li></ul><p><strong>Example</strong></p><pre>import kotlinx.coroutines.*<br><br>fun main() = runBlocking {<br>    println(&quot;Before launch&quot;)<br>    launch {<br>        try {<br>            // The risky code is now inside the try block<br>            println(&quot;Inside launch: Doing some work...&quot;)<br>            delay(500)<br>            throw RuntimeException(&quot;Oops, failed!&quot;)<br>        } catch (e: Exception) {<br>            // ✅ This block correctly catches the exception<br>            println(&quot;Caught exception inside launch: ${e.message}&quot;)<br>        }<br>    }<br>    println(&quot;After launch&quot;)<br>    delay(1000) // Wait for the launch to complete<br>    println(&quot;Main finished&quot;)<br>}</pre><p><strong>Output:</strong></p><pre>Before launch<br>After launch<br>Inside launch: Doing some work...<br>Caught exception inside launch: Oops, failed!<br>Main finished<br>... (stack trace) ...</pre><p>Here, the program handles the exception gracefully and doesn’t crash.</p><h3>Case 2: The async Builder</h3><p>async is used when you need to perform a task and get a result back later. This result is wrapped in a Deferred object. async handles exceptions differently—it &quot;holds&quot; the exception until you ask for the result.</p><h4>Incorrect: try-catch around the async call</h4><p>Just like launch, wrapping the async call itself in a try-catch does nothing.</p><ul><li><strong>Why?</strong>: async also returns immediately with a Deferred object. The exception happens later inside the coroutine and gets stored inside that Deferred object, waiting to be revealed.</li></ul><h4>Correct: try-catch around the .await() call</h4><p>The exception thrown inside async is only re-thrown when you call .await() to get the result. This is the moment of truth.</p><ul><li><strong>Why?</strong>: This design allows you to decide when and how to handle the potential failure. The exception is part of the “deferred” result.</li></ul><p><strong>Example</strong></p><pre>import kotlinx.coroutines.*<br><br>fun main() = runBlocking {<br>    println(&quot;Before async&quot;)<br>    val deferredResult: Deferred&lt;String&gt; = async {<br>        println(&quot;Inside async: About to fail...&quot;)<br>        delay(500)<br>        throw IllegalStateException(&quot;Async operation failed!&quot;)<br>        &quot;This will never be returned&quot;<br>    }<br>    println(&quot;After async&quot;)<br>    try {<br>        // The exception is thrown here, when we ask for the result<br>        val result = deferredResult.await()<br>        println(&quot;Result: $result&quot;)<br>    } catch (e: Exception) {<br>        // ✅ The exception is caught correctly here<br>        println(&quot;Caught exception on await: ${e.message}&quot;)<br>    }<br>    println(&quot;Main finished&quot;)<br>}</pre><p><strong>Output:</strong></p><pre>Before async<br>After async<br>Inside async: About to fail...<br>Caught exception on await: Async operation failed!<br>Main finished<br>Exception in thread &quot;main&quot; java.lang.IllegalStateException: Async operation failed!<br>... (stack trace) ...</pre><h4>Alternative: try-catch inside async</h4><ul><li><strong>Why?</strong>: try-catch Inside async can handle exceptions locally and based on the handling, one can return a result from the catch block itself. In this case, when a Deferred object is returned, it will never throw any exception as it was already handled.</li></ul><pre>import kotlinx.coroutines.*<br><br>fun main() = runBlocking {<br>    println(&quot;Before async&quot;)<br>    val deferredResult: Deferred&lt;String&gt; = async {<br>        println(&quot;Inside async: About to fail...&quot;)<br>        delay(500)<br>        throw IllegalStateException(&quot;Async operation failed!&quot;)<br>        &quot;This will never be returned&quot;<br>    }<br>    println(&quot;After async&quot;)<br>    try {<br>        // The exception is thrown here, when we ask for the result<br>        val result = deferredResult.await()<br>        println(&quot;Result: $result&quot;)<br>    } catch (e: Exception) {<br>        // ✅ The exception is caught correctly here<br>        println(&quot;Caught exception on await: ${e.message}&quot;)<br>    }<br>    println(&quot;Main finished&quot;)<br>}</pre><p><strong>Output:</strong></p><pre>Before async<br>After async<br>Inside async: About to fail...<br>Caught exception inside async: Async operation failed!<br>Result: Exception occurred inside aync<br>Main finished<br>... (stack trace) ...</pre><h3>Case 3: Parent-Child Relationships (coroutineScope)</h3><p>This is where structured concurrency really shines. A coroutineScope will wait for all its children to complete. If any child fails, the scope immediately cancels all other children and then fails itself.</p><h4>One Child Fails, All Fail</h4><ul><li><strong>Why?</strong>: This prevents work from continuing in an inconsistent state. If one crucial part of an operation fails, it’s often safer to cancel the entire operation.</li></ul><p><strong>Example</strong></p><pre>import kotlinx.coroutines.*<br><br>fun main() = runBlocking {<br>    println(&quot;Starting the scope...&quot;)<br>    try {<br>        coroutineScope { // Create a new scope<br>            launch {<br>                try {<br>                    println(&quot;Child 1: Working for 1000ms...&quot;)<br>                    delay(1000)<br>                    println(&quot;Child 1: Finished.&quot;) // This line will not be reached<br>                } finally {<br>                    println(&quot;Child 1: I was cancelled!&quot;)<br>                }<br>            }<br>            launch {<br>                println(&quot;Child 2: Working for 500ms then failing...&quot;)<br>                delay(500)<br>                throw RuntimeException(&quot;Child 2 failed!&quot;)<br>            }<br>        }<br>    } catch (e: Exception) {<br>        // The exception from Child 2 propagates up to the scope and is caught here<br>        println(&quot;Caught exception in parent scope: ${e.message}&quot;)<br>    }<br>    println(&quot;Scope finished.&quot;)<br>}</pre><p><strong>Output:</strong></p><pre>Starting the scope...<br>Child 1: Working for 1000ms...<br>Child 2: Working for 500ms then failing...<br>Child 1: I was cancelled!<br>Caught exception in parent scope: Child 2 failed!<br>Scope finished.<br>... (stack trace) ...</pre><p>As you can see, when Child 2 failed, Child 1 was immediately cancelled before it could finish its work.</p><h4>Nested Scope</h4><p>If we add another coroutine scope inside a coroutine scope, it will also be cancelled like any other jobs running inside the parent coroutine scope</p><h3>Case 4: Isolating Failures (supervisorScope)</h3><p>What if you don’t want one child’s failure to affect its siblings? For that, you use a supervisorScope.</p><ul><li><strong>Why?</strong>: A supervisorScope overrides the parent&#39;s cancellation policy. An exception from a direct child of a supervisorScope will <em>not</em> cancel the scope or its other children. This is perfect for UI applications where independent tasks are running, and one failing shouldn&#39;t freeze the entire screen.</li></ul><p><strong>Important Note</strong>: The supervision only applies to <em>direct children</em>. If you use a coroutineScope inside a supervisorScope, that inner coroutineScope will still follow its own &quot;cancel-all&quot; rule.</p><p><strong>Example</strong></p><pre>import kotlinx.coroutines.*<br><br>fun main() = runBlocking {<br>    println(&quot;Starting the supervisor scope...&quot;)<br>    try {<br>        supervisorScope { // Children failures are isolated<br>            launch {<br>                println(&quot;Child 1: Working for 500ms then failing...&quot;)<br>                delay(500)<br>                throw RuntimeException(&quot;Child 1 failed!&quot;)<br>            }<br>            launch {<br>                try {<br>                    println(&quot;Child 2: Working for 1000ms...&quot;)<br>                    delay(1000)<br>                    println(&quot;Child 2: Finished successfully!&quot;) // This line IS reached<br>                } finally {<br>                    println(&quot;Child 2: I was NOT cancelled!&quot;)<br>                }<br>            }<br>        }<br>    } catch (e: Exception) {<br>        // This catch block won&#39;t be hit because the supervisorScope<br>        // doesn&#39;t propagate the child&#39;s exception upwards.<br>        println(&quot;Caught exception in parent scope: $e&quot;)<br>    }<br>    println(&quot;Supervisor scope finished.&quot;)<br>}</pre><p><strong>Output:</strong></p><pre>Starting the supervisor scope...<br>Child 1: Working for 500ms then failing...<br>Child 2: Working for 1000ms...<br>Exception in thread &quot;main&quot; java.lang.RuntimeException: Child 1 failed! // The exception is still thrown, but uncaught<br>	... (stack trace) ...<br>Child 2: Finished successfully!<br>Child 2: I was NOT cancelled!<br>Supervisor scope finished.</pre><p>Wait, the program still crashed! Why? Because the exception from Child 1 wasn’t handled <em>anywhere</em>. The supervisorScope prevents cancellation, but it doesn&#39;t magically swallow the exception. You still need to handle it with the child who fails.</p><p><strong>Correct Way to use </strong><strong>supervisorScope</strong></p><p>You must handle exceptions within the children of a supervisorScope.</p><pre>import kotlinx.coroutines.*<br><br>fun main() = runBlocking {<br>    println(&quot;Starting the supervisor scope...&quot;)<br>    supervisorScope {<br>        // Child 1 with its own exception handling<br>        launch {<br>            try {<br>                println(&quot;Child 1: I&#39;m going to fail.&quot;)<br>                delay(500)<br>                throw RuntimeException(&quot;Child 1 failed!&quot;)<br>            } catch (e: Exception) {<br>                println(&quot;Caught in Child 1: ${e.message}&quot;)<br>            }<br>        }<br>        // Child 2 runs independently<br>        launch {<br>            println(&quot;Child 2: I will succeed.&quot;)<br>            delay(1000)<br>            println(&quot;Child 2: Finished successfully!&quot;)<br>        }<br>    }<br>    println(&quot;Supervisor scope finished.&quot;)<br>}</pre><p><strong>Output:</strong></p><pre>Starting the supervisor scope...<br>Child 1: I&#39;m going to fail.<br>Child 2: I will succeed.<br>Caught in Child 1: Child 1 failed!<br>Child 2: Finished successfully!<br>Supervisor scope finished.</pre><p>Now it works perfectly! Child 1 failed and handled its own error, while Child 2 completed its work unaffected.</p><h3>Case 5: The Global Catcher (CoroutineExceptionHandler)</h3><p>This is your last line of defense. A CoroutineExceptionHandler is a special context element that you can add to a top-level scope to catch any exceptions that were not handled otherwise.</p><ul><li><strong>When to Use</strong>: It’s primarily for logging, reporting errors, or performing cleanup for uncaught exceptions. It is most effective with launch in a CoroutineScope that uses a SupervisorJob or in GlobalScope.</li><li><strong>When It Doesn’t Work</strong>: It won’t work on children of a regular coroutineScope because the parent gets cancelled and handles the exception itself. It won’t work for async because the exception is held within the Deferred object, waiting for .await().</li></ul><p><strong>Example</strong></p><pre>import kotlinx.coroutines.*<br><br>fun main() = runBlocking {<br>    // 1. Create the handler<br>    val handler = CoroutineExceptionHandler { _, exception -&gt;<br>        println(&quot;Caught by CoroutineExceptionHandler: $exception&quot;)<br>    }<br>    // 2. Create a scope with a SupervisorJob and the handler<br>    // A SupervisorJob is like a supervisorScope for a whole scope.<br>    val scope = CoroutineScope(SupervisorJob() + handler)<br>    // This launch will fail, and the handler will catch it<br>    scope.launch {<br>        println(&quot;Child 1: Failing...&quot;)<br>        throw AssertionError(&quot;Something is wrong!&quot;)<br>    }<br>    // This launch will succeed, unaffected by the first one&#39;s failure<br>    scope.launch {<br>        delay(500)<br>        println(&quot;Child 2: I&#39;m alive!&quot;)<br>    }.join() // wait for child 2 to finish for a clean exit<br>    delay(1000) // Give time for the handler to run<br>    println(&quot;Main finished.&quot;)<br>}</pre><p><strong>Output:</strong></p><pre>Child 1: Failing...<br>Caught by CoroutineExceptionHandler: java.lang.AssertionError: Something is wrong!<br>Child 2: I&#39;m alive!<br>Main finished.</pre><p>The handler caught the error, and the second child was not cancelled, all thanks to the SupervisorJob.</p><h3>Case 6: async Within a supervisorScope</h3><p>We learned that supervisorScope prevents one failing child from cancelling its siblings. But how does this work with async? The rule for async remains the same: the exception is stored in the Deferred object and only thrown when you call .await().</p><ul><li><strong>Why it Matters</strong>: The supervisorScope ensures that if one async operation fails internally, other sibling coroutines (both launch and async) keep running. However, the responsibility of handling the failed async operation&#39;s exception still lies with the code that calls .await().</li></ul><p><strong>Example</strong></p><pre>import kotlinx.coroutines.*<br><br>fun main() = runBlocking {<br>    println(&quot;Starting supervisor scope with async...&quot;)<br>    supervisorScope {<br>        // First async operation, destined to fail<br>        val deferredFailure = async {<br>            println(&quot;Async 1: I will fail in 500ms.&quot;)<br>            delay(500)<br>            throw IllegalStateException(&quot;Failure!&quot;)<br>        }<br>        // Second async operation, which will succeed<br>        val deferredSuccess = async {<br>            println(&quot;Async 2: I will succeed in 1000ms.&quot;)<br>            delay(1000)<br>            &quot;Success!&quot;<br>        }<br>        // Try to await the result of the failing async<br>        try {<br>            deferredFailure.await()<br>        } catch (e: Exception) {<br>            println(&quot;Caught expected failure from Async 1: ${e.message}&quot;)<br>        }<br>        // Awaiting the successful async works perfectly fine, it was not cancelled<br>        try {<br>            val result = deferredSuccess.await()<br>            println(&quot;Result from Async 2: $result&quot;)<br>        } catch (e: Exception) {<br>            println(&quot;Caught unexpected failure from Async 2: $e&quot;)<br>        }<br>    }<br>    println(&quot;Supervisor scope finished.&quot;)<br>}</pre><p><strong>Output:</strong></p><pre>Starting supervisor scope with async...<br>Async 1: I will fail in 500ms.<br>Async 2: I will succeed in 1000ms.<br>Caught expected failure from Async 1: Failure!<br>Result from Async 2: Success!<br>Supervisor scope finished.</pre><p>This shows that deferredSuccess was not affected by deferredFailure&#39;s exception, but we still had to handle the exception at the await call site.</p><h3>Case 7: Cancellation is a Special Kind of Exception</h3><p>When a coroutine is cancelled, it throws a CancellationException. This is a special exception that is mostly ignored by coroutine machinery.</p><ul><li><strong>Why it Matters</strong>: A CancellationException signals that the coroutine was cancelled as expected, which is a normal part of structured concurrency. While you <em>can</em> catch it in a try-catch block, you generally <strong>should not swallow it</strong>. If you catch it to perform some action, you should re-throw it so the cancellation process can complete properly. The best place for cleanup logic is the finally block.</li></ul><p><strong>Example</strong></p><pre>import kotlinx.coroutines.*<br><br>fun main() = runBlocking {<br>    val job = launch {<br>        try {<br>            println(&quot;Job: I&#39;m working...&quot;)<br>            delay(2000) // This is a suspension point<br>            println(&quot;Job: I&#39;m done.&quot;) // This will never be printed<br>        } catch (e: CancellationException) {<br>            // This is okay for logging, but you must re-throw it!<br>            println(&quot;Job: I was cancelled. Re-throwing exception.&quot;)<br>            throw e<br>        } catch (e: Exception) {<br>            println(&quot;Job: Caught some other exception: $e&quot;)<br>        } finally {<br>            // ✅ This is the correct place for cleanup logic<br>            println(&quot;Job: Finally block executed for cleanup.&quot;)<br>        }<br>    }<br>    delay(1000)<br>    println(&quot;Main: I&#39;m tired of waiting, cancelling the job.&quot;)<br>    job.cancelAndJoin() // Cancel the job and wait for it to finish<br>    println(&quot;Main: Job has been cancelled.&quot;)<br>}</pre><p><strong>Output:</strong></p><pre>Job: I&#39;m working...<br>Main: I&#39;m tired of waiting, cancelling the job.<br>Job: I was cancelled. Re-throwing exception.<br>Job: Finally block executed for cleanup.<br>Main: Job has been cancelled.</pre><h3>Case 8: Unstoppable Cleanup with NonCancellable</h3><p>What if your cleanup code in the finally block is also a suspending function (like writing to a file or a network call)? If the coroutine is already cancelled, any new suspending call inside it will immediately throw a CancellationException.</p><ul><li><strong>Solution</strong>: To run a suspending function in a cleanup block, you must switch to a NonCancellable context. This guarantees that the code inside this block will run to completion without being cancelled.</li></ul><p><strong>Example</strong></p><pre>import kotlinx.coroutines.*<br><br>fun main() = runBlocking {<br>    val job = launch {<br>        try {<br>            println(&quot;Job: Working...&quot;)<br>            delay(2000)<br>        } finally {<br>            println(&quot;Job: Entering finally block.&quot;)<br>            // This suspending call would fail without NonCancellable<br>            withContext(NonCancellable) {<br>                println(&quot;Job: Starting crucial cleanup that takes 500ms...&quot;)<br>                delay(500) // Simulate a suspending cleanup operation<br>                println(&quot;Job: Crucial cleanup finished.&quot;)<br>            }<br>        }<br>    }<br>    delay(1000)<br>    println(&quot;Main: Cancelling the job.&quot;)<br>    job.cancelAndJoin()<br>    println(&quot;Main: Job cancelled.&quot;)<br>}</pre><p><strong>Output:</strong></p><pre>Job: Working...<br>Main: Cancelling the job.<br>Job: Entering finally block.<br>Job: Starting crucial cleanup that takes 500ms...<br>Job: Crucial cleanup finished.<br>Main: Job cancelled.</pre><p>Even though the job was cancelled, the suspending delay(500) inside the NonCancellable block was allowed to complete.</p><h3>Case 9: Nested Scopes &amp; Propagation</h3><p>The rules of coroutineScope (fail-all) and supervisorScope (isolate-failure) become even more interesting when you nest them. The key is to remember that the rules apply to the <em>immediate children</em> of that scope.</p><h4>coroutineScope inside supervisorScope</h4><p>An exception inside the inner coroutineScope will cancel its own siblings, but it will <strong>not</strong> cancel other children of the outer supervisorScope.</p><p><strong>Example</strong></p><pre>import kotlinx.coroutines.*<br><br>fun main() = runBlocking {<br>    // Top-level scope that isolates its direct children&#39;s failures<br>    supervisorScope {<br>        // First child of supervisorScope, this will not be cancelled<br>        launch {<br>            delay(1000)<br>            println(&quot;Supervisor&#39;s Child 1: I survived!&quot;)<br>        }<br>        // Second child of supervisorScope, which contains its own strict scope<br>        coroutineScope {<br>            launch {<br>                delay(600)<br>                // This sibling will be cancelled by the failure below<br>                println(&quot;Inner Scope Sibling: I will be cancelled.&quot;)<br>            }<br>            launch {<br>                delay(300)<br>                println(&quot;Inner Scope Failing Child: I&#39;m about to fail!&quot;)<br>                throw RuntimeException(&quot;Failure in inner scope&quot;)<br>            }<br>        }<br>    }<br>    println(&quot;All done.&quot;)<br>}</pre><p><strong>Output:</strong></p><pre>Inner Scope Failing Child: I&#39;m about to fail!<br>Supervisor&#39;s Child 1: I survived!<br>All done.<br>Exception in thread &quot;main&quot; java.lang.RuntimeException: Failure in inner scope<br>...</pre><p>Notice “Supervisor’s Child 1” printed its message, proving it was unaffected. But “Inner Scope Sibling” did not, because its sibling inside the coroutineScope failed. The exception still crashes the program because it was never caught.</p><h3>Case 10: The Job Hierarchy in Detail 🌳</h3><p>At the core of structured concurrency is the concept of a <strong>Job hierarchy</strong>. Think of it as a tree of tasks.</p><ul><li>When you launch a coroutine inside another coroutine (or a scope), the new coroutine’s Job becomes a <strong>child</strong> of the parent coroutine&#39;s Job.</li><li>A parent Job has two key responsibilities:</li></ul><ol><li>It waits for all its children to complete before it can complete.</li><li>If a child fails with an exception (and it’s not a supervisorScope), the parent cancels all other children and then fails itself.</li></ol><p>This parent-child link is what makes coroutines “structured” and prevents you from losing track of them.</p><p><strong>Example Visualization</strong></p><pre>import kotlinx.coroutines.*<br><br>fun main() = runBlocking { // This creates the root Job (parent)<br>    println(&quot;Parent Scope: I&#39;m the parent job.&quot;)<br>    // Child Job 1<br>    val job1 = launch {<br>        println(&quot;  Child 1: I&#39;m a child of the parent scope.&quot;)<br>        delay(1000)<br>        println(&quot;  Child 1: I&#39;m done.&quot;)<br>    }<br>    // Child Job 2<br>    val job2 = launch {<br>        println(&quot;  Child 2: I&#39;m also a child.&quot;)<br>        delay(500)<br>        // Let&#39;s create a grandchild<br>        launch {<br>            println(&quot;    Grandchild: My parent is Child 2.&quot;)<br>            delay(500)<br>            println(&quot;    Grandchild: I&#39;m done.&quot;)<br>        }<br>        println(&quot;  Child 2: I&#39;m done.&quot;)<br>    }<br>    println(&quot;Parent Scope: Waiting for my children to finish.&quot;)<br>} // The runBlocking scope will not finish until job1 and job2 are complete.</pre><p><strong>Output:</strong></p><pre>Parent Scope: I&#39;m the parent job.<br>Parent Scope: Waiting for my children to finish.<br>  Child 1: I&#39;m a child of the parent scope.<br>  Child 2: I&#39;m also a child.<br>    Grandchild: My parent is Child 2.<br>  Child 2: I&#39;m done.<br>    Grandchild: I&#39;m done.<br>  Child 1: I&#39;m done.</pre><p>Here, runBlocking is the parent. It only finishes after both job1 and job2 (and job2&#39;s own child) are complete.</p><h3>Case 11: supervisorScope vs. CoroutineScope(SupervisorJob())</h3><p>This is a subtle but important architectural distinction.</p><ul><li>supervisorScope { ... }: You use this <strong>builder</strong> to create a localized bubble where failures don&#39;t spread. It&#39;s for isolating a <em>group of related tasks</em>. If an exception inside this scope is uncaught, it still propagates <em>outside</em> the supervisorScope block.</li><li>CoroutineScope(SupervisorJob()): You create a <strong>scope object</strong> with this. Any coroutines launched directly from this scope object are independent. This pattern is ideal for components with a lifecycle that manage multiple independent, top-level tasks (like a server or an Android ViewModel). A failure in one task will not destroy the scope itself or other tasks.</li></ul><p><strong>Example: A ViewModel-like Scope</strong></p><pre>import kotlinx.coroutines.*<br><br>// This class simulates a long-living component like an Android ViewModel or a server.<br>class Component {<br>    // Create a scope for this component. Its Job is a SupervisorJob.<br>    // An uncaught exception will be handled by the handler, but the scope itself remains active.<br>    private val scope = CoroutineScope(SupervisorJob() + CoroutineExceptionHandler { _, throwable -&gt;<br>        println(&quot;Component Scope: Caught an error: $throwable&quot;)<br>    })<br>    // This task might fail, but it won&#39;t affect other tasks in the scope.<br>    fun startRiskyTask() {<br>        scope.launch {<br>            println(&quot;Risky Task: Starting...&quot;)<br>            delay(500)<br>            throw RuntimeException(&quot;Something went wrong!&quot;)<br>        }<br>    }<br>    // This task can be started independently and will continue to run.<br>    fun startStableTask() {<br>        scope.launch {<br>            println(&quot;Stable Task: I&#39;m running...&quot;)<br>            delay(1500)<br>            println(&quot;Stable Task: I finished successfully.&quot;)<br>        }<br>    }<br>    fun destroy() {<br>        println(&quot;Component: Destroying and cancelling scope.&quot;)<br>        scope.cancel() // Cancel all coroutines when the component is destroyed.<br>    }<br>}<br>fun main() = runBlocking {<br>    val component = Component()<br>    component.startRiskyTask()<br>    component.startStableTask()<br>    delay(2000) // Let the tasks run for a while.<br>    component.destroy()<br>    delay(500)<br>}</pre><p><strong>Output:</strong></p><pre>Risky Task: Starting...<br>Stable Task: I&#39;m running...<br>Component Scope: Caught an error: java.lang.RuntimeException: Something went wrong!<br>Stable Task: I finished successfully.<br>Component: Destroying and cancelling scope.</pre><p>Even though the risky task failed, the stable task completed successfully because the scope used a SupervisorJob. The scope itself remained active until destroy() was called.</p><h3>Case 12: Handling Timeouts ⏰</h3><p>Long-running operations can be a problem. Coroutines provide a clean way to enforce a time limit.</p><ul><li>withTimeout(timeMillis) { ... }: This runs a block of code and throws a TimeoutCancellationException if it doesn&#39;t complete within the specified time. This is a subclass of CancellationException, so it cancels the coroutine.</li><li>withTimeoutOrNull(timeMillis) { ... }: This is a non-throwing alternative. If the time limit is exceeded, it stops the coroutine and returns null instead of throwing an exception. This is often cleaner to handle.</li></ul><p><strong>Example</strong></p><pre>import kotlinx.coroutines.*<br><br>fun main() = runBlocking {<br>    // Using withTimeout (throws exception)<br>    try {<br>        withTimeout(1000L) {<br>            println(&quot;Task 1: I have 1 second to complete.&quot;)<br>            delay(1500L) // This will take too long<br>            println(&quot;Task 1: I finished.&quot;) // This won&#39;t be printed<br>        }<br>    } catch (e: TimeoutCancellationException) {<br>        println(&quot;Task 1 failed: ${e.message}&quot;)<br>    }<br>    println(&quot;---&quot;)<br>    // Using withTimeoutOrNull (returns null)<br>    val result = withTimeoutOrNull(1000L) {<br>        println(&quot;Task 2: I also have 1 second.&quot;)<br>        delay(1500L) // Again, too long<br>        &quot;Success&quot; // This value will not be returned<br>    }<br>    if (result == null) {<br>        println(&quot;Task 2 timed out and returned null.&quot;)<br>    } else {<br>        println(&quot;Task 2 finished with result: $result&quot;)<br>    }<br>}</pre><p><strong>Output:</strong></p><pre>Task 1: I have 1 second to complete.<br>Task 1 failed: Timed out waiting for 1000 ms<br>---<br>Task 2: I also have 1 second.<br>Task 2 timed out and returned null.</pre><h3>Case 13: Exceptions When Awaiting Multiple Jobs</h3><p>What if you start several async jobs and wait for them all? The awaitAll() extension function is perfect for this.</p><ul><li><strong>Behavior</strong>: If any of the async jobs you are awaiting fails, awaitAll() will immediately cancel all the other jobs and re-throw the exception from the one that failed. It follows the &quot;all-or-nothing&quot; principle, just like coroutineScope.</li></ul><p><strong>Example</strong></p><pre>import kotlinx.coroutines.*<br><br>fun main() = runBlocking {<br>    println(&quot;Starting multiple async jobs.&quot;)<br>    try {<br>        coroutineScope { // A scope is needed to launch coroutines<br>            val deferred1 = async {<br>                delay(1000)<br>                println(&quot;Job 1: Success.&quot;)<br>                &quot;Result 1&quot;<br>            }<br>            val deferred2 = async {<br>                delay(500)<br>                println(&quot;Job 2: Failing!&quot;)<br>                throw IllegalStateException(&quot;Job 2 Error&quot;)<br>            }<br>            val deferred3 = async {<br>                delay(1200)<br>                // This will be cancelled before it can complete<br>                println(&quot;Job 3: Success.&quot;)<br>                &quot;Result 3&quot;<br>            }<br>            // Wait for all of them to complete<br>            val results = awaitAll(deferred1, deferred2, deferred3)<br>            println(&quot;All results: $results&quot;)<br>        }<br>    } catch (e: Exception) {<br>        println(&quot;Caught exception in awaitAll: ${e.message}&quot;)<br>    }<br>}</pre><p><strong>Output:</strong></p><pre>Starting multiple async jobs.<br>Job 2: Failing!<br>Job 1: Success.<br>Caught exception in awaitAll: Job 2 Error</pre><p>As you can see, the moment Job 2 failed, awaitAll threw its exception. Job 3, which was still running, was cancelled as a result. Job 1 had already been completed, so its message was printed.</p><p>So this is all about exception handling in coroutines. Hope you find this article interesting. <br>For any questions or queries, let’s connect on LinkedIn</p><p><a href="https://www.linkedin.com/in/devbaljeet/">https://www.linkedin.com/in/devbaljeet/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d4538158ab5" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/the-golden-rule-of-coroutine-exceptions-8d4538158ab5">The Golden Rule of Coroutine Exceptions</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sealed Class & Data Class in Kotlin — How it works Internally]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/kotlindevs/sealed-class-data-class-in-kotlin-how-it-works-internally-555fd264bc86?source=rss-ee347576cb25------2"><img src="https://cdn-images-1.medium.com/max/2600/1*12FuChK9YUHvKK-xf5j4cQ.png" width="2816"></a></p><p class="medium-feed-snippet">In Kotlin development, sealed classes and data classes have become fundamental tools for building robust and expressive applications&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/kotlindevs/sealed-class-data-class-in-kotlin-how-it-works-internally-555fd264bc86?source=rss-ee347576cb25------2">Continue reading on KotlinDevs »</a></p></div>]]></description>
            <link>https://medium.com/kotlindevs/sealed-class-data-class-in-kotlin-how-it-works-internally-555fd264bc86?source=rss-ee347576cb25------2</link>
            <guid isPermaLink="false">https://medium.com/p/555fd264bc86</guid>
            <category><![CDATA[android-apps]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Baljeet Singh]]></dc:creator>
            <pubDate>Tue, 09 Sep 2025 10:32:56 GMT</pubDate>
            <atom:updated>2025-09-09T10:32:56.578Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Jetpack Compose 1.9: The Game-Changing Update Every Android Developer Needs to Know About]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/kotlindevs/jetpack-compose-1-9-the-game-changing-update-every-android-developer-needs-to-know-about-14a9b995da70?source=rss-ee347576cb25------2"><img src="https://cdn-images-1.medium.com/max/2048/1*mFpCO3hNSrS4OhCrGZ5tJw.png" width="2048"></a></p><p class="medium-feed-snippet">Remember the days when adding a simple drop shadow to your Android views required creating custom drawable XML files, dealing with&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/kotlindevs/jetpack-compose-1-9-the-game-changing-update-every-android-developer-needs-to-know-about-14a9b995da70?source=rss-ee347576cb25------2">Continue reading on KotlinDevs »</a></p></div>]]></description>
            <link>https://medium.com/kotlindevs/jetpack-compose-1-9-the-game-changing-update-every-android-developer-needs-to-know-about-14a9b995da70?source=rss-ee347576cb25------2</link>
            <guid isPermaLink="false">https://medium.com/p/14a9b995da70</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-apps]]></category>
            <dc:creator><![CDATA[Baljeet Singh]]></dc:creator>
            <pubDate>Sun, 07 Sep 2025 18:34:41 GMT</pubDate>
            <atom:updated>2025-09-07T18:34:41.031Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Android 16 Migration Hacks: The Developer’s Survival Guide]]></title>
            <link>https://proandroiddev.com/android-16-migration-hacks-the-developers-survival-guide-81c3722bb122?source=rss-ee347576cb25------2</link>
            <guid isPermaLink="false">https://medium.com/p/81c3722bb122</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[android-16]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Baljeet Singh]]></dc:creator>
            <pubDate>Thu, 28 Aug 2025 09:10:55 GMT</pubDate>
            <atom:updated>2025-09-15T00:50:10.494Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rbALErdJ6-kFD75WhWNK0g.png" /></figure><h3>Saving Your Sanity (and Codebase) When Upgrading to API 36</h3><p>Let’s be real — every Android version upgrade feels like defusing a bomb while blindfolded. Android 16 (API level 36) is no exception, introducing breaking changes that can render your perfectly functioning app useless, akin to a digital paperweight. But here’s the thing: you don’t need to rewrite half your codebase. After digging through the developer preview, beta releases, and countless Stack Overflow threads, I’ve compiled the battle-tested hacks that will save you weeks of refactoring.</p><h3>JobScheduler Quota Hell: Bypassing Strict Enforcement</h3><p>Android 16 enforces JobScheduler quotas more strictly, even when your app has a foreground service running. Your background jobs might start failing silently.</p><h3>The Smart Workaround</h3><p>Instead of refactoring all your jobs, implement a hybrid approach:</p><pre>class SmartJobScheduler(private val context: Context) {<br>    <br>    fun scheduleJob(jobInfo: JobInfo.Builder) {<br>        val scheduler = context.getSystemService(JobScheduler::class.java)<br>        <br>        // Check if we&#39;re approaching quota limits<br>        if (isApproachingQuota()) {<br>            // Fallback to WorkManager for non-critical jobs<br>            convertToWorkManager(jobInfo)<br>        } else {<br>            scheduler.schedule(jobInfo.build())<br>        }<br>    }<br>    <br>    private fun isApproachingQuota(): Boolean {<br>        // Track your job executions in SharedPrefs<br>        val recentJobs = getRecentJobCount()<br>        return recentJobs &gt; 45 // Stay under the 50 job limit<br>    }<br>    <br>    private fun convertToWorkManager(jobInfo: JobInfo.Builder) {<br>        val workRequest = OneTimeWorkRequestBuilder&lt;FallbackWorker&gt;()<br>            .setInputData(jobInfo.toWorkData())<br>            .build()<br>        WorkManager.getInstance(context).enqueue(workRequest)<br>    }<br>}</pre><h3>The Orientation Apocalypse: How to Keep Your App From Spinning Out of Control</h3><p>Android 16’s most controversial change? Your manifest orientation restrictions are basically worthless on large screens now. Apps targeting API 36 must be fully adaptive on displays with smallest width ≥ 600dp. No more forcing portrait mode on tablets.</p><h3>The Nuclear Option</h3><p>If you absolutely can’t support adaptive layouts yet, use this temporary escape hatch:</p><pre>&lt;!-- In your AndroidManifest.xml --&gt;<br>&lt;application&gt;<br>    &lt;meta-data <br>        android:name=&quot;android.window.PROPERTY_COMPAT_ALLOW_ORIENTATION_OVERRIDE&quot;<br>        android:value=&quot;true&quot; /&gt;<br>&lt;/application&gt;</pre><p><strong>Warning</strong>: This is a temporary fix. Google will likely remove this in Android 17, so start planning your adaptive layouts now.</p><h3>Material 3 Expressive: Preventing the UI Explosion</h3><p>The new Material 3 Expressive design language brings aggressive animations and blur effects that can break your custom components. Instead of updating everything, selectively disable the problematic features:</p><h3>The Compatibility Bridge</h3><pre>// Create a theme override for Android 16+<br>&lt;!-- res/values-v36/themes.xml --&gt;<br>&lt;resources&gt;<br>    &lt;style name=&quot;AppTheme&quot; parent=&quot;Theme.Material3.DayNight&quot;&gt;<br>        &lt;!-- Disable aggressive animations --&gt;<br>        &lt;item name=&quot;android:windowActivityTransitions&quot;&gt;false&lt;/item&gt;<br>        &lt;item name=&quot;android:windowContentTransitions&quot;&gt;false&lt;/item&gt;<br>        <br>        &lt;!-- Reduce blur intensity --&gt;<br>        &lt;item name=&quot;android:windowBackgroundBlurRadius&quot;&gt;0dp&lt;/item&gt;<br>        <br>        &lt;!-- Keep your existing color scheme --&gt;<br>        &lt;item name=&quot;android:forceDarkAllowed&quot;&gt;false&lt;/item&gt;<br>    &lt;/style&gt;<br>&lt;/resources&gt;</pre><h3>Animation Performance Hack</h3><p>If Material 3 animations are causing jank:</p><pre>// Add to Application class<br>override fun onCreate() {<br>    super.onCreate()<br>    <br>    if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.VANILLA_ICE_CREAM) {<br>        // Reduce animation scales for smoother performance<br>        ValueAnimator.setDurationScale(0.7f)<br>        <br>        // Disable window blur on low-end devices<br>        if (isLowRamDevice()) {<br>            window.decorView.setRenderEffect(null)<br>        }<br>    }<br>}</pre><h3>Camera API Changes: The Motion Photo Trap</h3><p>Android 16’s enhanced camera support includes automatic motion photo capture, which can bloat your app’s storage usage unexpectedly.</p><h3>The Storage Saver</h3><pre>class CameraCompat {<br>    fun captureImage(context: Context) {<br>        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE).apply {<br>            if (Build.VERSION.SDK_INT &gt;= 36) {<br>                // Disable motion photos by default<br>                putExtra(&quot;android.provider.extra.MOTION_PHOTO_MODE&quot;, false)<br>                // Disable night mode auto-detection if not needed<br>                putExtra(&quot;android.provider.extra.NIGHT_MODE_AUTO&quot;, false)<br>            }<br>        }<br>        context.startActivityForResult(intent, REQUEST_IMAGE_CAPTURE)<br>    }<br>}</pre><h3>The Vulkan Graphics Bomb</h3><p>With Vulkan becoming the official graphics API, older OpenGL ES code might start showing deprecation warnings or performance issues.</p><h3>The Dual-Renderer Pattern</h3><p>Instead of rewriting your renderer, implement a fallback system:</p><pre>class GraphicsRenderer {<br>    private val renderer = if (shouldUseVulkan()) {<br>        VulkanRenderer() // New implementation<br>    } else {<br>        GLESRenderer() // Your existing code<br>    }<br>    <br>    private fun shouldUseVulkan(): Boolean {<br>        return Build.VERSION.SDK_INT &gt;= 36 &amp;&amp; <br>               hasVulkanSupport() &amp;&amp; <br>               !userDisabledVulkan()<br>    }<br>}</pre><h3>Night Mode Theme Crashes: The Hidden Landmine</h3><p>Android 16 changes how night mode resources are resolved, potentially causing crashes in edge cases. The fix that took me hours to find:</p><h3>The Universal Fix</h3><pre>// Always provide both theme variants<br>&lt;!-- res/values/themes.xml --&gt;<br>&lt;style name=&quot;AppTheme&quot; parent=&quot;Theme.Material3.DayNight.NoActionBar&quot;&gt;<br>    &lt;!-- Your day theme --&gt;<br>&lt;/style&gt;<br>&lt;!-- res/values-night/themes.xml --&gt;<br>&lt;style name=&quot;AppTheme&quot; parent=&quot;Theme.Material3.DayNight.NoActionBar&quot;&gt;<br>    &lt;!-- Your night theme --&gt;<br>&lt;/style&gt;<br>&lt;!-- res/values-night-v36/themes.xml --&gt;<br>&lt;style name=&quot;AppTheme&quot; parent=&quot;Theme.Material3.DayNight.NoActionBar&quot;&gt;<br>    &lt;!-- Android 16 specific night theme overrides --&gt;<br>    &lt;item name=&quot;android:colorBackground&quot;&gt;@color/background_night_v36&lt;/item&gt;<br>&lt;/style&gt;</pre><h3>The Predictive Back Gesture Time Bomb</h3><p>Android 16 makes predictive back gesture mandatory for apps targeting API 36. But here’s how to implement it with minimal changes:</p><h3>The Lazy Developer’s Implementation</h3><pre>class BackCompatActivity : AppCompatActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        <br>        if (Build.VERSION.SDK_INT &gt;= 36) {<br>            onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {<br>                override fun handleOnBackStarted(backEvent: BackEvent) {<br>                    // Minimal animation - just fade<br>                    window.decorView.animate()<br>                        .alpha(0.8f)<br>                        .setDuration(200)<br>                        .start()<br>                }<br>                <br>                override fun handleOnBackProgressed(backEvent: BackEvent) {<br>                    // Skip complex animations<br>                }<br>                <br>                override fun handleOnBackPressed() {<br>                    // Your existing back logic<br>                    handleBackNavigation()<br>                }<br>                <br>                override fun handleOnBackCancelled() {<br>                    // Reset the fade<br>                    window.decorView.animate()<br>                        .alpha(1f)<br>                        .setDuration(100)<br>                        .start()<br>                }<br>            })<br>        }<br>    }<br>}</pre><h3>Performance Optimisation Shortcuts</h3><h3>1. Adaptive Refresh Rate Hack</h3><p>Android 16’s adaptive refresh rate can cause stuttering in games or video apps. Force a consistent frame rate:</p><pre>window.attributes = window.attributes.apply {<br>    if (Build.VERSION.SDK_INT &gt;= 36) {<br>        // Force 60fps for consistency<br>        preferredRefreshRate = 60f<br>    }<br>}</pre><h3>2. HDR Screenshot Workaround</h3><p>If HDR screenshots are breaking your app’s screenshot functionality:</p><pre>fun captureScreenshot() {<br>    if (Build.VERSION.SDK_INT &gt;= 36) {<br>        // Temporarily disable HDR for screenshot<br>        window.colorMode = ActivityInfo.COLOR_MODE_DEFAULT<br>        performScreenshot()<br>        // Re-enable HDR after capture<br>        window.colorMode = ActivityInfo.COLOR_MODE_HDR<br>    }<br>}</pre><h3>The Testing Shortcut You Need</h3><p>Instead of updating your targetSdkVersion immediately, use the compatibility framework to test specific changes:</p><pre># Test orientation changes without changing targetSdk<br>adb shell am compat enable OVERRIDE_ORIENTATION_RESTRICTIONS com.yourapp<br># Test JobScheduler strict quota<br>adb shell am compat enable ENFORCE_JOB_SCHEDULER_QUOTAS com.yourapp<br># Test all Android 16 behaviors<br>adb shell am compat enable-all com.yourapp</pre><h3>Emergency Rollback Strategy</h3><p>If things go catastrophically wrong after updating:</p><pre>android {<br>    compileSdk 36<br>    <br>    defaultConfig {<br>        targetSdk 35 // Keep targeting Android 15 temporarily<br>        <br>        // But test with Android 16 behaviors<br>        testOptions {<br>            targetSdk 36<br>        }<br>    }<br>    <br>    // Create a separate build variant for Android 16<br>    flavorDimensions &quot;api&quot;<br>    productFlavors {<br>        api35 {<br>            dimension &quot;api&quot;<br>            targetSdk 35<br>        }<br>        api36 {<br>            dimension &quot;api&quot;<br>            targetSdk 36<br>        }<br>    }<br>}</pre><h3>The Bottom Line</h3><p>Android 16 isn’t just another update — it’s a paradigm shift toward adaptive, responsive apps. But you don’t need to panic-refactor everything. These hacks will buy you time to properly implement the changes while keeping your app functional.</p><p>Remember: Google typically gives you 12–18 months before enforcing new target SDK requirements on the Play Store. Use this time wisely:</p><ol><li><strong>Months 1–3</strong>: Apply these quick fixes</li><li><strong>Months 4–9</strong>: Gradually implement proper solutions</li><li><strong>Months 10–12</strong>: Test thoroughly and polish</li><li><strong>Month 13+</strong>: You’re ready for the enforcement deadline</li></ol><p>The key is to stay calm, test incrementally, and remember that every Android developer is going through the same pain. These hacks aren’t perfect solutions, but they’ll keep your app alive while you plan your proper migration strategy.</p><p>Stay strong, and may you build.gradle always syncs on the first try.</p><p><em>Found these hacks helpful? Follow me for more Android survival guides. Got your own Android 16 workarounds? Drop them in the comments — we’re all in this together.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81c3722bb122" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/android-16-migration-hacks-the-developers-survival-guide-81c3722bb122">Android 16 Migration Hacks: The Developer’s Survival Guide</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>