<?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 Harshali Sachani on Medium]]></title>
        <description><![CDATA[Stories by Harshali Sachani on Medium]]></description>
        <link>https://medium.com/@harshalisachani?source=rss-d131f66caa76------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DElIsQpS1cGG60YHX_7kPA.jpeg</url>
            <title>Stories by Harshali Sachani on Medium</title>
            <link>https://medium.com/@harshalisachani?source=rss-d131f66caa76------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 22:32:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@harshalisachani/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[Navigating Kotlin’s Type System: A Guide to Type Checks and Casts with ‘is’ and ‘as’]]></title>
            <link>https://medium.com/learn-to-earn/navigating-kotlins-type-system-a-guide-to-type-checks-and-casts-with-is-and-as-0368ae9e4337?source=rss-d131f66caa76------2</link>
            <guid isPermaLink="false">https://medium.com/p/0368ae9e4337</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin-type-cast]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Harshali Sachani]]></dc:creator>
            <pubDate>Mon, 15 Jan 2024 18:23:23 GMT</pubDate>
            <atom:updated>2024-01-15T18:23:23.380Z</atom:updated>
            <content:encoded><![CDATA[<h4>Type Checks and Casts in Kotlin: The ‘is’ and ‘as’ Chronicles</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0MlFhiKi1v-TMJwkg3Q52Q.png" /></figure><h4><strong>Have you ever crossed your path with Kotlin Type Checks and Cast? </strong>🤔</h4><p>Kotlin comes with one of <strong>common exception type casting with null safety</strong> but you can get rid of this using the right way and making a smooth type casting process.</p><p>Let me first give you a brief introduction. We have</p><blockquote><strong>is</strong> for Type Check and</blockquote><blockquote><strong>as </strong>for Cast</blockquote><p>— These operators play a pivotal role in Kotlin type system. To enhance your code readability, maintainability and writing efficient and safe kotlin code with type safety we should understand how to use <strong>is</strong> and <strong>as</strong>operators significantly.</p><p>In this blog, we’ll understand usage with examples.</p><p>Consider <strong>obj</strong>as <strong>Any</strong> type object in Kotlin throughout examples.</p><h3>`is` and `!is` operators</h3><h4>Type checking</h4><p>With <strong>is</strong> operator you can check if an object is an instance of particular type or not.</p><pre>if (obj is String) {<br>    print(“it is a String”)<br>} else {<br>    print(“it is not String”)<br>}</pre><p>You can use <strong>!is</strong> operator to check type visa-versa</p><pre>if (obj !is String) { <br>    print(&quot;it is not String&quot;)<br>} </pre><h4>Smart cast magic 🪄</h4><p>Kotlin is smart — <strong>is operator </strong>isn’t just about checks, it automatically cast variable to that type within the corresponding block. We’ll understand with example:</p><pre>if (obj is String) {<br>        // obj is automatically cast to String<br>        print(obj.length)     <br>}</pre><p>Kotlin knows that within the “if” block variable is treated as <strong>String </strong>type and allows access to <strong><em>String specific functions</em></strong>. It eliminates the need for explicit casting and makes your code more concise and expressive.</p><blockquote><strong>More usage:</strong><em> </em><strong><em>Smart casts work with </em></strong><strong><em>when expressions and </em></strong><strong><em>while loops as well</em></strong></blockquote><h3>`as` and `as?` Operator</h3><p>While <strong>is</strong> focuses on type checking and smart casting, the <strong>as</strong> <strong>operator</strong> comes into play for <strong><em>explicit casting</em></strong>. It’s a very interesting scenarios while using <strong>as</strong>and <strong>as?</strong> operators. Use it wisely otherwise you might put your life at risk. 😃</p><blockquote>Relax, I’ll not let you put your life at risk. It’s precious we still have to face lots of bugs and invalidate cache. ☠</blockquote><h4>`as` as Unsafe cast operator</h4><p>For scenarios where you are certain about the type <strong>as</strong> <strong>operator</strong> can be used for non-nullable casting. Thus, it’s called an unsafe cast operator throws an exception if the cast isn’t possible.</p><pre>val stringValue: String = obj as String</pre><p>If obj is null, then it can not be cast to String because <strong>stringValue </strong>type is non-nullable and it throws an exception.</p><blockquote><strong>java.lang.NullPointerException: null cannot be cast to non-null type kotlin.String</strong></blockquote><p>To handle this scenario use nullable type:</p><pre>val stringValue: String? = obj as String?</pre><p>But, there will be one more scenario-scenario-scenario. It hangs my mind and android-studio as well. 💫</p><p>What if obj is not a String type?</p><blockquote><strong>java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String</strong></blockquote><p>Let’s understand it</p><h4>`as?` as Safe cast operator</h4><p>Here <strong>as? operator</strong> comes as savior in nullability and type safety conversation. It is a warrior 🛠</p><pre>val stringValue: String? = obj as? String<br>print(&quot;stringValue=$stringValue&quot;)</pre><blockquote><strong>It runs without failed but stringValue variable is null type</strong></blockquote><blockquote>Output : stringValue=null</blockquote><p>By using <strong>as?</strong> You are safe from risking your life at runtime exceptions and gracefully handle scenarios where cast might not be possible.</p><h3>📖 Best Practices for Seamless Type Handling:</h3><ol><li><strong>Clarity with </strong><strong>is: </strong>Use <strong>is</strong> for clear and straightforward type checks to enhance code readability and simplicity.</li><li><strong>Safety First with </strong><strong>as?:</strong> When casting, especially from Any to a specific type, prefer the safe cast <strong>as?</strong> to handle potential type mismatches gracefully</li><li><strong>Mindful Non-Nullable Casting:</strong> Reserve the non-nullable cast operator <strong>as</strong> for situations where you are certain about the type, minimizing the risk of runtime exceptions.</li></ol><h3>📌Conclusion</h3><p>Deep understanding of <strong>is </strong>and <strong>as</strong> operators in Kotlin opens the door to writing more expressive, concise and type-safe code. mastering these operators is a key step toward becoming more proficient in the Kotlin language and unlocking the full potential of Kotlin’s type system.</p><p>🙏I hope these article were useful while using type check and cast operator.</p><p>Feel free to customize in your way or if you have any better suggestions it’s warmly welcomed! Please comment below your thoughts. 💬</p><p>👏 Please clap if you found this article helpful.</p><p>Thank you for reading this article. 🙂</p><p>Happy coding !! 💪 👩‍💻</p><p>🌐Connect on <a href="https://www.linkedin.com/in/harshalisachani">https://www.linkedin.com/in/harshalisachani</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0368ae9e4337" width="1" height="1" alt=""><hr><p><a href="https://medium.com/learn-to-earn/navigating-kotlins-type-system-a-guide-to-type-checks-and-casts-with-is-and-as-0368ae9e4337">Navigating Kotlin’s Type System: A Guide to Type Checks and Casts with ‘is’ and ‘as’</a> was originally published in <a href="https://medium.com/learn-to-earn">Learn To Earn</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Room migrations]]></title>
            <link>https://medium.com/learn-to-earn/understanding-room-migrations-701c42ff6892?source=rss-d131f66caa76------2</link>
            <guid isPermaLink="false">https://medium.com/p/701c42ff6892</guid>
            <category><![CDATA[room-database-migration]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-room-database]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Harshali Sachani]]></dc:creator>
            <pubDate>Fri, 29 Dec 2023 19:23:52 GMT</pubDate>
            <atom:updated>2023-12-29T19:23:52.610Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to deal with manual Room Database migration?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5mMnoI8U_pcS9COs" /><figcaption>Photo by <a href="https://unsplash.com/@tofi?utm_source=medium&amp;utm_medium=referral">Tobias Fischer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Successfully <a href="https://developer.android.com/training/data-storage/room"><strong>Room Database</strong></a> migration feels like I’ve defused a bomb 😀 — Doesn’t it? It’s so stressful to move users from one version to another for some complex migrations.</p><p>Room support <a href="https://developer.android.com/training/data-storage/room/migrating-db-versions#automated"><strong>Automated Migration</strong></a> for following case:</p><ul><li>@DeleteTable</li><li>@RenameTable</li><li>@DeleteColumn</li><li>@RenameColumn</li></ul><p>If app needs more requirement other than this we need to manage manual migrations because Room not able to migrate complex schema changes. And the read struggle start from here 🤷‍♀️</p><p>Let’s take one simple example where we have a <strong>User </strong>table, with two columns:</p><pre>@Entity(tableName = &quot;User&quot;)<br>data class UserModel(<br>    @PrimaryKey(autoGenerate = true) var id: Long = 0L,<br>    @ColumnInfo(name = &quot;user_name&quot;) var userName: String? = null,<br>}</pre><p>Consider we just create this table and database with version 1</p><pre>@Database(entities = [UserModel::class], version = 1)<br><br><br>// create database builder<br>val database = Room.databaseBuilder(context, AppDatabase::class.java, &quot;AppDatabase&quot;)<br>                   .build()</pre><p>🎉 And here your database is created with <strong>User </strong>table</p><p>Now we add new column in <strong>User </strong>table to manage <a href="https://developer.android.com/training/data-storage/room/migrating-db-versions#manual"><strong>Manual Room Database Migration</strong></a></p><pre>@Entity(tableName = &quot;UserModel&quot;)<br>data class UserModel(<br>    @PrimaryKey(autoGenerate = true) var id: Long = 0L,<br>    @ColumnInfo(name = &quot;user_name&quot;) var userName: String? = null,<br>    @ColumnInfo(name = &quot;email&quot;) var email: String? = null,<br>}</pre><p>If we try to run app it will crash with this error 👾</p><blockquote>java.lang.IllegalStateException: Room cannot verify the data integrity. Looks like you’ve changed schema but forgot to update the version number. You can simply fix this by increasing the version number</blockquote><p>Now we will change Room Database version</p><pre>@Database(entities = [UserModel::class], version = 2)</pre><p>Still it will gives an error 👾</p><blockquote>java.lang.IllegalStateException: A migration from 1 to 2 is necessary. Please provide a Migration in the builder or call fallbackToDestructiveMigration in the builder in which case Room will re-create all of the tables.</blockquote><p>Here, If you don’t want to manual migrations and you want your database to be cleared when you upgrade the version, call <a href="https://developer.android.com/training/data-storage/room/prepopulate#ex-fallback"><strong>fallbackToDestructiveMigration()</strong></a> in the database builder like below:</p><pre>val database = Room.databaseBuilder(context, AppDatabase::class.java, &quot;AppDatabase&quot;)<br>                   .fallbackToDestructiveMigration() <br>                   .build()</pre><p>👏 Well done! App will run without fail now.</p><p>But if you want migration without lose all your previous version data follow manual migration process below :</p><p>First create migration variable and write migration query</p><pre>private val MIGRATION_1_2 = object : Migration(1, 2) {<br>    override fun migrate(database: SupportSQLiteDatabase) {<br>        database.execSQL(&quot;ALTER TABLE UserModel ADD COLUMN &#39;email&#39; TEXT&quot;)<br>    }<br>}</pre><p>Add migration variable to database builder</p><pre>val database = Room.databaseBuilder(context, AppDatabase::class.java, &quot;AppDatabase&quot;)<br>                   .addMigrations(MIGRATION_1_2)                   <br>                   .build()</pre><p>🎊 Finally, Now run app it will run without fail with migration</p><p>You can write multiple migration query in single version. Let’s say we add new table <strong>AddressModel </strong>and add new column in<strong> UserModel </strong>table.</p><pre>@Entity(tableName = &quot;AddressModel&quot;)<br>data class AddressModel(<br>   @PrimaryKey(autoGenerate = true) var id: Long = 0L,<br>   @ColumnInfo(name = &quot;city&quot;) var city: String? = null,<br>   @ColumnInfo(name = &quot;country&quot;) var country: String? = null,<br>}<br><br> private val MIGRATION_2_3 = object : Migration(2, 3) {<br>     override fun migrate(database: SupportSQLiteDatabase) {<br>         database.execSQL(&quot;ALTER TABLE UserModel ADD COLUMN &#39;phone_no&#39; TEXT&quot;)<br>         database.execSQL(&quot;CREATE TABLE IF NOT EXISTS `AddressModel` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `city` TEXT, `country` TEXT)<br><br>     }<br>}</pre><p><strong>Add this migration to database builder and don’t forgot to change version number.</strong></p><p>🤔 What if user have an older version of app with database version 1 and upgrade to database version 3? So, we already added migration from 1–2 and 2–3. Room will trigger all migrations one by one.</p><p>We can also define manually migration for more than one version increment. Write migration variable below.</p><pre>private val MIGRATION_1_3 = object : Migration(1, 3) {<br>    override fun migrate(database: SupportSQLiteDatabase) {<br>        database.execSQL(&quot;ALTER TABLE UserModel ADD COLUMN &#39;email&#39; TEXT&quot;)<br>        database.execSQL(&quot;ALTER TABLE UserModel ADD COLUMN &#39;phone_no&#39; TEXT&quot;)<br>        database.execSQL(&quot;CREATE TABLE IF NOT EXISTS `Address` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `city` TEXT, `country` TEXT)<br><br>    }<br>}</pre><p>Add this migration to your database builder</p><pre>val database = Room.databaseBuilder(context, AppDatabase::class.java, &quot;AppDatabase&quot;)<br>                   .addMigrations(MIGRATION_1_2,MIGRATION_2_3,MIGRATION_1_3  )                   <br>                   .build()</pre><h3>Best Practices 📖</h3><p>While migrating Room Database manually follow these 3 steps to get rid of any errors or failure</p><ol><li><strong>Increase database version number</strong></li><li><strong>Write migration query in variable</strong></li><li><strong>Add migration variable in database builder</strong></li></ol><h3>Conclusion 📌</h3><p>If you follow all steps wisely while migrating the database you will succeed in defusing the bomb otherwise your app will explode.</p><p>I hope these article were useful in migrating Room Database in complex changes. 🙏</p><p>Feel free to customize in your way or if you have any better suggestions it’s warmly welcomed! Please comment below your thoughts. 💬</p><p>Thank you for reading this article. 👏</p><p>Happy coding !! 💪 👩‍💻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=701c42ff6892" width="1" height="1" alt=""><hr><p><a href="https://medium.com/learn-to-earn/understanding-room-migrations-701c42ff6892">Understanding Room migrations</a> was originally published in <a href="https://medium.com/learn-to-earn">Learn To Earn</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use Kotlin Extension function?]]></title>
            <link>https://medium.com/learn-to-earn/how-to-use-kotlin-extension-function-88096e9e3dbc?source=rss-d131f66caa76------2</link>
            <guid isPermaLink="false">https://medium.com/p/88096e9e3dbc</guid>
            <category><![CDATA[kotlin-for-android]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-extension]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[extension-functions]]></category>
            <dc:creator><![CDATA[Harshali Sachani]]></dc:creator>
            <pubDate>Mon, 04 Dec 2023 03:34:03 GMT</pubDate>
            <atom:updated>2023-12-21T15:58:07.344Z</atom:updated>
            <content:encoded><![CDATA[<h4>Enhance android developing using custom Extension function.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*u4wPIWi8l39cniY1" /><figcaption>Photo by <a href="https://unsplash.com/@weareambitious?utm_source=medium&amp;utm_medium=referral">Ambitious Studio* - Rick Barrett</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://kotlinlang.org/docs/android-overview.html">Kotlin</a> is a versatile programming language that offers numerous features to make Android development more efficient and enjoyable. One of its standout features is <strong>extension functions</strong>. <br>…And I loved to use and create custom Extension Function for continuous use. <br>First we should know about <strong>How </strong><a href="https://kotlinlang.org/docs/extensions.html"><strong>Kotlin Extension Functions</strong></a><strong> works internally</strong> let me give you quick introduction,</p><blockquote>Extension functions allow you to extend the behavior of existing classes without modifying their source code. This feature can significantly improve your Android app development process, making your code more concise and expressive.</blockquote><p>In this article We’ll create Custom Kotlin Extension Function for repeatedly used functions. So, now let’s check out some Examples,</p><h3>1. Show Toast Message</h3><p>Commonly we use Toast in our application to show some message, warning or hint in same case and we use <strong>makeText </strong>function of <strong>Toast </strong>class and pass Context, String, Duration every time.</p><p>But, with extension function we can make it more convenient.</p><pre>fun Context.showToast(s: String, duration: Int = Toast.LENGTH_SHORT) {<br>    Toast.makeText(this, s, duration).show()<br>}<br><br>fun Context.showToast(@StringRes stringRes: Int, duration: Int = Toast.LENGTH_SHORT) {<br>    Toast.makeText(this, stringRes, duration).show()<br>}</pre><p><strong>Usage</strong></p><pre>showToast(&quot;Toast Message&quot;), duration)<br>toast(R.string.toast_message)</pre><h3><strong>2. Get ApplicationInfo and PackageInfo</strong></h3><p>Sometimes we need to get <strong>ApplicationInfo </strong>and <strong>PackageInfo </strong>to get app data. We are already aware about various Android API level deprecation, when we get certain info from package we need to add SDK condition because latest API did not support old method. We can use Extension Function to getting rid of writing this SDK condition everywhere.</p><pre>fun PackageManager.getApplicationInfoCompat(packageName: String, flags: Int = 0): ApplicationInfo =<br>    if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.TIRAMISU) {<br>        getApplicationInfo(packageName, PackageManager.ApplicationInfoFlags.of(flags.toLong()))<br>    } else {<br>        @Suppress(&quot;DEPRECATION&quot;) getApplicationInfo(packageName, flags)<br>    }<br><br>fun PackageManager.appsPackageInfo(packageName: String): PackageInfo =<br>    if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.TIRAMISU) {<br>        getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(0))<br>    } else {<br>        @Suppress(&quot;DEPRECATION&quot;) getPackageInfo(packageName, 0)<br>    }<br><br>fun PackageManager.appsApplicationInfo(packageName: String): ApplicationInfo =<br>    if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.P) {<br>        getApplicationInfoCompat(packageName, PackageManager.GET_SIGNING_CERTIFICATES)<br>    } else {<br>        @Suppress(&quot;DEPRECATION&quot;) getApplicationInfoCompat(packageName, PackageManager.GET_SIGNATURES)<br>    }<br><br>fun PackageManager.appsVersionCode(packageName: String): Int =<br>    if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.P) {<br>        appsPackageInfo(packageName).longVersionCode.toInt()<br>    } else {<br>        @Suppress(&quot;DEPRECATION&quot;) appsPackageInfo(packageName).versionCode<br>    }<br><br>fun PackageManager.appsVersionName(packageName: String): String =<br>    this.appsPackageInfo(packageName).versionName</pre><p><strong>Usage</strong></p><pre>// You can use lambda for packageManager instance<br>packageManager?.let { pm -&gt;<br>    pm.appsVersionCode(packageName)<br>    pm.appsVersionName(packageName)<br>    pm.getApplicationLabel(packageManager.appsApplicationInfo(packageName))<br>}<br><br>// OR use packageManager instance every-time while get appinfo <br>packageManager.appsVersionCode(packageName)<br>packageManager.appsVersionName(packageName)<br>packageManager.getApplicationLabel(packageManager.appsApplicationInfo(packageName))</pre><h3><strong>3. Fallback default value</strong></h3><p>In our app often we need to check null value and set fallback default value. <strong>ifNullOrEmpty </strong>extension function return self string if given string is non-null or else pass `defaultValue` lamda, and we can use this lamda to assign our default fallback value.</p><pre>inline fun String?.ifNullOrEmpty(defaultValue: () -&gt; String): String {<br>    return if (!isNullOrEmpty()) this<br>    else defaultValue()<br>}</pre><p><strong>Usage</strong></p><pre>var s: String? = null<br>/* we decalre variable type nullable and in some case,<br>and we need fallback value if value is null then we can use it */<br>val language = s.ifNullOrEmpty { &quot;kotlin&quot; }</pre><h3><strong>4. Parcelable and Serializable in Intent and Bundle</strong></h3><p>Usually we pass <a href="https://developer.android.com/reference/android/content/Intent#getParcelableExtra(java.lang.String)">Parcelable </a>and <a href="https://developer.android.com/reference/android/content/Intent#getSerializableExtra(java.lang.String)">Serializable</a> data in <a href="https://developer.android.com/reference/android/content/Intent">intent</a>. In latest android APIs this method is deprecated and when we upgrade our app to latest SDK we added API level condition and use latest method for higher SDK. We can make extension function to make it more simple.</p><pre>inline fun &lt;reified T : java.io.Serializable&gt; Bundle.serializable(key: String): T? = when {<br>    Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.TIRAMISU -&gt; getSerializable(key, T::class.java)<br>    else -&gt; @Suppress(&quot;DEPRECATION&quot;) getSerializable(key) as? T<br>}<br><br>inline fun &lt;reified T : Serializable&gt; Intent.serializable(key: String): T? = when {<br>    Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.TIRAMISU -&gt; getSerializableExtra(key, T::class.java)<br>    else -&gt; @Suppress(&quot;DEPRECATION&quot;) getSerializableExtra(key) as? T<br>}<br><br>inline fun &lt;reified T : Parcelable&gt; Intent.parcelable(key: String): T? = when {<br>    Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.TIRAMISU -&gt; getParcelableExtra(key, T::class.java)<br>    else -&gt; @Suppress(&quot;DEPRECATION&quot;) getParcelableExtra(key) as? T<br>}<br><br>inline fun &lt;reified T : Parcelable&gt; Bundle.parcelable(key: String): T? = when {<br>    Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.TIRAMISU -&gt; getParcelable(key, T::class.java)<br>    else -&gt; @Suppress(&quot;DEPRECATION&quot;) getParcelable(key) as? T<br>}</pre><p><strong>Usage</strong></p><pre>// Consider Person as Data Class which we pass through parcelabel or serializable<br>// in intent as required<br>val person: Person = intent.parcelable&lt;Person&gt;(&quot;Person_Data&quot;) as Person<br>val person: Person = intent.serializable&lt;Person&gt;(&quot;Person_Data&quot;) as Person</pre><h3><strong>5. StartActivity with Intent Extra</strong></h3><p>While setting up intent with data we can use this extension function. With lambda extension approach we can use this function with and without extra.</p><pre>inline fun &lt;reified T : Activity&gt; Context.startActivity(block: Intent.() -&gt; Unit = {}) {<br>    startActivity(Intent(this, T::class.java).apply(block))<br>}</pre><p><strong>Usage</strong></p><pre>startActivity&lt;MainActivity&gt;()<br><br>// with extra<br>startActivity&lt;MainActivity&gt; {<br>    putExtra(&quot;key name&quot;, &quot;value&quot;)<br>}</pre><h3>Benefits of Extension Functions ⚡</h3><p>Using extension functions in Android development offers several advantages:</p><ol><li><strong>Code Reusability</strong>: You can write a function once and use it across your entire project, reducing code duplication.</li><li><strong>Improved Readability</strong>: Extension functions make your code more readable and expressive by encapsulating complex logic in a self-contained manner.</li><li><strong>Easier Testing</strong>: You can write unit tests for extension functions independently, enhancing the testability of your code.</li><li><strong>Maintainability</strong>: By encapsulating specific behaviors in extension functions, you can make future changes or updates more manageable.</li></ol><h3>Best Practices 📖</h3><p>While extension functions are powerful, it’s essential to follow some best practices:</p><ol><li><strong>Clear Naming</strong>: Use meaningful names for your extension functions to ensure clarity.</li><li><strong>Keep It Simple</strong>: Keep extension functions focused and avoid adding too much complexity to a single function.</li><li><strong>Avoid Overusing</strong>: Don’t overuse extension functions to extend numerous classes; they should be used judiciously.</li><li><strong>Mind Ambiguity</strong>: Be cautious about potential ambiguity when creating extension functions for classes with similar names.</li></ol><h3><strong>Conclusion </strong>📌</h3><p>These are mainly used Kotlin Extension Functions in android development. I hope these functions were useful in simplifying and optimizing your code. 🙏</p><p>Feel free to customize in your way or if you have any better suggestions it’s warmly welcomed! Please comment below your thoughts. 💬</p><p>Thank you for reading this article. 👏</p><p>Happy coding !! 💪 👩‍💻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88096e9e3dbc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/learn-to-earn/how-to-use-kotlin-extension-function-88096e9e3dbc">How to use Kotlin Extension function?</a> was originally published in <a href="https://medium.com/learn-to-earn">Learn To Earn</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>