<?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 Tung Doan on Medium]]></title>
        <description><![CDATA[Stories by Tung Doan on Medium]]></description>
        <link>https://medium.com/@doanthanhtungnk123?source=rss-55f8aed942a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_FvPblhKvMjxk8c8IefjOw.jpeg</url>
            <title>Stories by Tung Doan on Medium</title>
            <link>https://medium.com/@doanthanhtungnk123?source=rss-55f8aed942a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 09:47:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@doanthanhtungnk123/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[Why Room Crashes When You Change Your Database (And How to Fix It)]]></title>
            <link>https://proandroiddev.com/why-room-crashes-when-you-change-your-database-and-how-to-fix-it-ca8e3538bf57?source=rss-55f8aed942a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca8e3538bf57</guid>
            <category><![CDATA[database-schema]]></category>
            <category><![CDATA[room-database]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[migration]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Tung Doan]]></dc:creator>
            <pubDate>Sat, 17 Jan 2026 04:32:20 GMT</pubDate>
            <atom:updated>2026-01-17T16:00:53.000Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XUIP2YAXP5F6H1c5Pgx1yw.png" /></figure><p>If you’ve worked with Room in Android, you’ve probably seen this dreaded error:</p><pre>Room cannot verify the data integrity. Looks like you&#39;ve changed schema but forgot to update the version number.</pre><p>Most developers just increment the version number and move on. But what’s actually happening behind the scenes? Why does Room care so much about schema changes? And what exactly is this “hash” it keeps talking about?</p><p>Let’s go deep.</p><h3>Table of Contents</h3><ol><li>What is a Database Schema?</li><li>How Room Tracks Schema: The Identity Hash</li><li>Where the Hash Lives: room_master_table</li><li>Why Room Crashes on Schema Mismatch</li><li>The Migration System Explained</li><li>fallbackToDestructiveMigration: What It Really Does</li><li>When to Use Each Migration Strategy</li><li>Auto-Migrations in Room 2.4+</li><li>Schema Export and Version Control</li><li>Common Pitfalls and Best Practices</li></ol><h3>1. What is a Database Schema?</h3><p>A <strong>schema</strong> is the blueprint of your database. It defines:</p><ul><li><strong>Tables</strong> — What tables exist</li><li><strong>Columns</strong> — Name, type, nullable, default value</li><li><strong>Primary Keys</strong> — Unique identifier for each row</li><li><strong>Foreign Keys</strong> — Relationships between tables</li><li><strong>Indices</strong> — For faster queries</li><li><strong>Constraints</strong> — NOT NULL, UNIQUE, CHECK, etc.</li></ul><p>In Room, your schema is defined by your @Entity classes:</p><pre>@Entity(<br>    tableName = &quot;users&quot;,<br>    indices = [Index(value = [&quot;email&quot;], unique = true)]<br>)<br>data class UserEntity(<br>    @PrimaryKey(autoGenerate = true)<br>    val id: Long = 0,<br>    @ColumnInfo(name = &quot;email&quot;)<br>    val email: String,<br>    @ColumnInfo(name = &quot;name&quot;)<br>    val name: String,<br>    @ColumnInfo(name = &quot;created_at&quot;)<br>    val createdAt: Long = System.currentTimeMillis()<br>)</pre><p>Room reads these annotations at <strong>compile time</strong> and generates:</p><ol><li>SQL CREATE TABLE statements</li><li>DAO implementations</li><li>A <strong>schema identity hash</strong></li></ol><h3>2. How Room Tracks Schema: The Identity Hash</h3><p>Here’s where it gets interesting.</p><p>At compile time, Room generates a <strong>hash string</strong> that uniquely represents your entire database schema. This hash is calculated from:</p><ul><li>All table names</li><li>All column names, types, and constraints</li><li>All indices</li><li>All foreign keys</li><li>All views</li><li>The order of everything</li></ul><h3>How the Hash is Generated</h3><p>Room collects all schema information and creates a deterministic string representation:</p><pre>// Simplified conceptual example<br>schemaString = &quot;&quot;&quot;<br>    TABLE users (<br>        id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,<br>        email TEXT NOT NULL,<br>        name TEXT NOT NULL,<br>        created_at INTEGER NOT NULL<br>    )<br>    INDEX index_users_email ON users(email) UNIQUE<br>    TABLE posts (<br>        id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,<br>        user_id INTEGER NOT NULL,<br>        content TEXT,<br>        FOREIGN KEY (user_id) REFERENCES users(id)<br>    )<br>&quot;&quot;&quot;<br><br>identityHash = SHA-256(schemaString)  // e.g., &quot;a3f2b8c9d4e5f6a7b8c9d0e1f2a3b4c5&quot;</pre><p>This hash is then <strong>hardcoded</strong> into the generated _Impl class:</p><pre>// Generated by Room: AppDatabase_Impl.java<br>@Override<br>protected SupportSQLiteOpenHelper createOpenHelper(DatabaseConfiguration configuration) {<br>    return new RoomOpenHelper(<br>        configuration,<br>        new RoomOpenHelper.Delegate(2) {  // version<br>            @Override<br>            public void createAllTables(SupportSQLiteDatabase _db) {<br>                // CREATE TABLE statements...<br>            }<br>            @Override<br>            protected void validateMigration(SupportSQLiteDatabase _db) {<br>                // Schema validation...<br>            }<br>        },<br>        &quot;a3f2b8c9d4e5f6a7b8c9d0e1f2a3b4c5&quot;,  // ← THE IDENTITY HASH<br>        &quot;d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2&quot;   // ← Legacy hash (pre-Room 2.2)<br>    );<br>}</pre><h3>What Changes the Hash?</h3><p><strong>ANY</strong> schema modification changes the hash:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*QRTdYXsPC8fjMMC3uP69nQ.png" /><figcaption>Room schema modification changes the hash</figcaption></figure><h3>3. Where the Hash Lives: room_master_table</h3><p>When Room creates your database for the first time, it creates a special internal table:</p><pre>CREATE TABLE room_master_table (<br>    id INTEGER PRIMARY KEY,<br>    identity_hash TEXT<br>);<br><br>INSERT INTO room_master_table (id, identity_hash)<br>VALUES (42, &#39;a3f2b8c9d4e5f6a7b8c9d0e1f2a3b4c5&#39;);</pre><p>This table has exactly <strong>one row</strong> with:</p><ul><li>id = 42 (always 42, it&#39;s hardcoded)</li><li>identity_hash = the schema hash when the database was created/migrated</li></ul><p>You can actually see this yourself:</p><pre>// Debug: Query the room_master_table<br>@Dao<br>interface DebugDao {<br>    @Query(&quot;SELECT identity_hash FROM room_master_table WHERE id = 42&quot;)<br>    fun getSchemaHash(): String<br>}</pre><p>Or via Android Studio’s Database Inspector:</p><pre>SELECT * FROM room_master_table;<br>-- Result: id=42, identity_hash=&quot;a3f2b8c9d4e5f6a7b8c9d0e1f2a3b4c5&quot;</pre><h3>4. Why Room Crashes on Schema Mismatch</h3><p>Now we understand the full picture. Here’s what happens on every app launch:</p><h3>The Verification Process</h3><pre>┌─────────────────────────────────────────────────────────┐<br>│                    APP LAUNCHES                         │<br>└─────────────────────────────────────────────────────────┘<br>                           │<br>                           ▼<br>┌─────────────────────────────────────────────────────────┐<br>│  Room opens the database file                           │<br>└─────────────────────────────────────────────────────────┘<br>                           │<br>                           ▼<br>┌─────────────────────────────────────────────────────────┐<br>│  Query: SELECT identity_hash FROM room_master_table     │<br>│  Result: &quot;abc123...&quot; (hash stored in database file)     │<br>└─────────────────────────────────────────────────────────┘<br>                           │<br>                           ▼<br>┌─────────────────────────────────────────────────────────┐<br>│  Compare with compiled hash in AppDatabase_Impl         │<br>│  Compiled hash: &quot;xyz789...&quot; (from current code)         │<br>└─────────────────────────────────────────────────────────┘<br>                           │<br>                           ▼<br>                    ┌──────────────┐<br>                    │  Match?      │<br>                    └──────────────┘<br>                      │          │<br>                     YES         NO<br>                      │          │<br>                      ▼          ▼<br>               ┌──────────┐  ┌──────────────────────┐<br>               │ Continue │  │ Check version number │<br>               │ normally │  └──────────────────────┘<br>               └──────────┘           │<br>                                      ▼<br>                              ┌───────────────┐<br>                              │ Version same? │<br>                              └───────────────┘<br>                                │           │<br>                               YES          NO<br>                                │           │<br>                                ▼           ▼<br>                         ┌──────────┐  ┌────────────────┐<br>                         │  CRASH!  │  │ Run migrations │<br>                         └──────────┘  └────────────────┘</pre><h3>The Crash Scenario</h3><p>When hashes don’t match AND version is the same:</p><pre>// Your code (version unchanged)<br>@Database(entities = [UserEntity::class], version = 1)<br><br>// But you added a field to UserEntity:<br>@Entity<br>data class UserEntity(<br>    @PrimaryKey val id: Long,<br>    val name: String,<br>    val email: String  // ← NEW FIELD!<br>)</pre><p>Room’s logic:</p><ol><li>Database file has hash &quot;abc123&quot; and version 1</li><li>Compiled code has hash &quot;xyz789&quot; and version 1</li><li>Hashes don’t match but versions are same</li><li>Room thinks: <em>“Schema changed but developer didn’t acknowledge it”</em></li><li><strong>CRASH</strong> with IllegalStateException</li></ol><h3>Why Crash Instead of Auto-Migrate?</h3><p>Room crashes intentionally because:</p><ol><li><strong>Data Safety</strong> — Auto-altering tables could lose data</li><li><strong>Explicit Acknowledgment</strong> — Developer must consciously handle changes</li><li><strong>No Guessing</strong> — Room can’t know if you want to migrate or reset</li><li><strong>Production Protection</strong> — Prevents accidental data loss in production</li></ol><p>The error message is actually Room being helpful:</p><pre>&quot;Hey, your schema changed but the version didn&#39;t.<br>Did you forget to update it? I&#39;m crashing now so you<br>notice this in development, not in production.&quot;</pre><h3>5. The Migration System Explained</h3><p>When you increment the version, Room looks for a migration path:</p><pre>@Database(entities = [UserEntity::class], version = 2)  // Was 1<br>abstract class AppDatabase : RoomDatabase()</pre><h3>Migration Path Resolution</h3><pre>Database file version: 1<br>Code version: 2<br><br>Room searches for: Migration(1, 2)</pre><p>If found, Room executes it:</p><pre>val MIGRATION_1_2 = object : Migration(1, 2) {<br>    override fun migrate(db: SupportSQLiteDatabase) {<br>        db.execSQL(&quot;ALTER TABLE users ADD COLUMN email TEXT&quot;)<br>    }<br>}</pre><h3>Multi-Step Migrations</h3><p>For version jumps, Room chains migrations:</p><pre>Database: version 1<br>Code: version 4<br><br>Room searches for path: 1 → 2 → 3 → 4<br>Executes: MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4</pre><p>Or you can provide a direct jump:</p><pre>val MIGRATION_1_4 = object : Migration(1, 4) {<br>    override fun migrate(db: SupportSQLiteDatabase) {<br>        // All changes from v1 to v4 in one migration<br>    }<br>}</pre><p>Room prefers the <strong>shortest path</strong>. If both exist:</p><ul><li>MIGRATION_1_2 + MIGRATION_2_3 + MIGRATION_3_4 (3 steps)</li><li>MIGRATION_1_4 (1 step)</li></ul><p>Room uses MIGRATION_1_4.</p><h3>What Happens Inside migrate()</h3><p>You have full SQL access:</p><pre>override fun migrate(db: SupportSQLiteDatabase) {<br>    // Add column<br>    db.execSQL(&quot;ALTER TABLE users ADD COLUMN age INTEGER NOT NULL DEFAULT 0&quot;)<br><br>    // Create new table<br>    db.execSQL(&quot;&quot;&quot;<br>        CREATE TABLE IF NOT EXISTS posts (<br>            id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,<br>            user_id INTEGER NOT NULL,<br>            content TEXT,<br>            FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE<br>        )<br>    &quot;&quot;&quot;)<br>    // Create index<br>    db.execSQL(&quot;CREATE INDEX index_posts_user_id ON posts(user_id)&quot;)<br>    // Copy data (for complex migrations)<br>    db.execSQL(&quot;&quot;&quot;<br>        INSERT INTO users_new (id, name, email)<br>        SELECT id, name, &#39;&#39; FROM users_old<br>    &quot;&quot;&quot;)<br>    // Drop old table<br>    db.execSQL(&quot;DROP TABLE users_old&quot;)<br>    // Rename table<br>    db.execSQL(&quot;ALTER TABLE users_new RENAME TO users&quot;)<br>}</pre><h3>Post-Migration Validation</h3><p>After migration completes, Room:</p><ol><li>Recalculates schema hash from actual database</li><li>Compares with compiled hash</li><li>If match → Updates room_master_table with new hash</li><li>If no match → <strong>CRASH</strong> (migration was incomplete/incorrect)</li></ol><pre>Migration complete<br>├── Actual DB hash: &quot;xyz789&quot;<br>├── Expected hash:  &quot;xyz789&quot;<br>├── Match? ✅<br>└── Update room_master_table SET identity_hash = &quot;xyz789&quot;</pre><h3>6. fallbackToDestructiveMigration: What It Really Does</h3><p>This is the “nuclear option”:</p><pre>Room.databaseBuilder(context, AppDatabase::class.java, &quot;app.db&quot;)<br>    .fallbackToDestructiveMigration()<br>    .build()</pre><h3>Under the Hood</h3><p>When enabled and no migration path exists:</p><pre>// Simplified Room internal logic<br>fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {<br>    val migrationPath = findMigrationPath(oldVersion, newVersion)<br><br>    if (migrationPath != null) {<br>        // Execute migrations normally<br>        migrationPath.forEach { it.migrate(db) }<br>    } else if (fallbackToDestructiveMigration) {<br>        // DESTROY EVERYTHING<br>        dropAllTables(db)<br>        createAllTables(db)<br>        // User data is GONE<br>    } else {<br>        throw IllegalStateException(&quot;Migration path not found&quot;)<br>    }<br>}<br>fun dropAllTables(db: SQLiteDatabase) {<br>    // Get all table names<br>    val cursor = db.rawQuery(<br>        &quot;SELECT name FROM sqlite_master WHERE type=&#39;table&#39; AND name NOT LIKE &#39;sqlite_%&#39;&quot;,<br>        null<br>    )<br>    // Drop each table<br>    cursor.use {<br>        while (it.moveToNext()) {<br>            val tableName = it.getString(0)<br>            if (tableName != &quot;room_master_table&quot; &amp;&amp; tableName != &quot;android_metadata&quot;) {<br>                db.execSQL(&quot;DROP TABLE IF EXISTS $tableName&quot;)<br>            }<br>        }<br>    }<br>}</pre><h3>What Gets Destroyed</h3><p>Destroyed Preserved All your tables room_master_table (recreated) All your data android_metadata All indices Database file itself All foreign keys</p><h3>Variants of Destructive Migration</h3><pre>// Destroy on ANY failed migration<br>.fallbackToDestructiveMigration()<br><br>// Destroy only when DOWNGRADING (e.g., version 3 → 2)<br>.fallbackToDestructiveMigrationOnDowngrade()<br><br>// Destroy only from specific versions<br>.fallbackToDestructiveMigrationFrom(1, 2, 3)</pre><h3>The Destruction Sequence</h3><pre>1. Room detects version change (1 → 2)<br>2. Room searches for Migration(1, 2)<br>3. Not found!<br>4. fallbackToDestructiveMigration is enabled<br>5. Room executes:<br>   - DROP TABLE users<br>   - DROP TABLE posts<br>   - DROP TABLE comments<br>   - (all tables dropped)<br>6. Room executes onCreate():<br>   - CREATE TABLE users (new schema)<br>   - CREATE TABLE posts (new schema)<br>   - etc.<br>7. Room updates room_master_table with new hash<br>8. Database is now empty but schema is correct</pre><h3>7. When to Use Each Migration Strategy</h3><h3>Decision Tree</h3><pre>Schema changed?<br>│<br>├── YES<br>│   │<br>│   ├── Development/Testing?<br>│   │   │<br>│   │   ├── YES → fallbackToDestructiveMigration() ✅<br>│   │   │         Fast iteration, don&#39;t care about data<br>│   │   │<br>│   │   └── NO (Production)<br>│   │       │<br>│   │       ├── Can lose data? (fresh install behavior OK?)<br>│   │       │   │<br>│   │       │   ├── YES → fallbackToDestructiveMigration() ⚠️<br>│   │       │   │         (Consider user experience)<br>│   │       │   │<br>│   │       │   └── NO → Write proper Migration() ✅<br>│   │       │<br>│   │       └── Complex schema change?<br>│   │           │<br>│   │           ├── YES → Consider Auto-Migration (Room 2.4+)<br>│   │           │<br>│   │           └── NO → Manual Migration()<br>│   │<br>│   └── Increment version number!<br>│<br>└── NO → Do nothing</pre><h3>Strategy Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*dt4yjGXrTwB6iYpGTQ1dZw.png" /><figcaption>Migration strategy Comparison</figcaption></figure><h3>When Destructive is Actually OK in Production</h3><ol><li><strong>First launch after install</strong> — No existing data</li><li><strong>Cache-only database</strong> — Data can be re-fetched</li><li><strong>Non-critical data</strong> — User won’t miss it</li><li><strong>Explicit user action</strong> — “Reset app data” feature</li></ol><pre>// Example: Cache database that can be rebuilt<br>@Database(entities = [CachedArticle::class], version = 2)<br>abstract class CacheDatabase : RoomDatabase()<br><br>// OK to use destructive - data is just a cache<br>Room.databaseBuilder(context, CacheDatabase::class.java, &quot;cache.db&quot;)<br>    .fallbackToDestructiveMigration()<br>    .build()</pre><h3>When You MUST Use Proper Migration</h3><ol><li><strong>User-generated content</strong> — Notes, messages, documents</li><li><strong>Purchase history</strong> — Transactions, receipts</li><li><strong>Authentication state</strong> — Tokens, sessions</li><li><strong>Preferences</strong> — Settings user configured</li><li><strong>Progress data</strong> — Game saves, completed tutorials</li></ol><h3>8. Auto-Migrations in Room 2.4+</h3><p>Room 2.4 introduced automatic migrations for simple schema changes:</p><pre>@Database(<br>    entities = [User::class],<br>    version = 2,<br>    autoMigrations = [<br>        AutoMigration(from = 1, to = 2)<br>    ]<br>)<br>abstract class AppDatabase : RoomDatabase()</pre><h3>What Auto-Migration Can Handle</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*569Rv4prqnnpc2dzwinCag.png" /><figcaption>What Auto-Migration Can Handle</figcaption></figure><h3>Auto-Migration with Spec</h3><p>For deletions and renames, provide a spec:</p><pre>@Database(<br>    entities = [User::class],<br>    version = 3,<br>    autoMigrations = [<br>        AutoMigration(from = 1, to = 2),<br>        AutoMigration(from = 2, to = 3, spec = Migration2To3::class)<br>    ]<br>)<br>abstract class AppDatabase : RoomDatabase()<br><br>@RenameColumn(tableName = &quot;users&quot;, fromColumnName = &quot;name&quot;, toColumnName = &quot;full_name&quot;)<br>@DeleteColumn(tableName = &quot;users&quot;, columnName = &quot;temp_field&quot;)<br>@RenameTable(fromTableName = &quot;user_data&quot;, toTableName = &quot;user_profiles&quot;)<br>class Migration2To3 : AutoMigrationSpec</pre><h3>How Auto-Migration Works Internally</h3><ol><li>Room compares schema of version N and N+1 at compile time</li><li>Generates SQL statements automatically</li><li>Creates a Migration class under the hood</li></ol><pre>// Generated: AppDatabase_AutoMigration_1_2_Impl.java<br>public class AppDatabase_AutoMigration_1_2_Impl extends Migration {<br>    public AppDatabase_AutoMigration_1_2_Impl() {<br>        super(1, 2);<br>    }<br><br>    @Override<br>    public void migrate(@NonNull SupportSQLiteDatabase database) {<br>        database.execSQL(&quot;ALTER TABLE users ADD COLUMN age INTEGER NOT NULL DEFAULT 0&quot;);<br>        database.execSQL(&quot;CREATE TABLE IF NOT EXISTS posts (...)&quot;);<br>    }<br>}</pre><h3>9. Schema Export and Version Control</h3><h3>Enabling Schema Export</h3><pre>@Database(<br>    entities = [User::class],<br>    version = 5,<br>    exportSchema = true  // Enable this!<br>)<br>abstract class AppDatabase : RoomDatabase()</pre><p>In build.gradle:</p><pre>android {<br>    defaultConfig {<br>        javaCompileOptions {<br>            annotationProcessorOptions {<br>                arguments += [&quot;room.schemaLocation&quot;: &quot;$projectDir/schemas&quot;]<br>            }<br>        }<br>    }<br>}<br><br>// For KSP<br>ksp {<br>    arg(&quot;room.schemaLocation&quot;, &quot;$projectDir/schemas&quot;)<br>}</pre><h3>What Gets Exported</h3><p>Room creates a JSON file for each version:</p><pre>app/schemas/<br>├── com.example.AppDatabase/<br>│   ├── 1.json<br>│   ├── 2.json<br>│   ├── 3.json<br>│   ├── 4.json<br>│   └── 5.json</pre><p>Example 5.json:</p><pre>{<br>  &quot;formatVersion&quot;: 1,<br>  &quot;database&quot;: {<br>    &quot;version&quot;: 5,<br>    &quot;identityHash&quot;: &quot;a3f2b8c9d4e5f6a7b8c9d0e1f2a3b4c5&quot;,<br>    &quot;entities&quot;: [<br>      {<br>        &quot;tableName&quot;: &quot;users&quot;,<br>        &quot;createSql&quot;: &quot;CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `email` TEXT NOT NULL)&quot;,<br>        &quot;fields&quot;: [<br>          {<br>            &quot;fieldPath&quot;: &quot;id&quot;,<br>            &quot;columnName&quot;: &quot;id&quot;,<br>            &quot;affinity&quot;: &quot;INTEGER&quot;,<br>            &quot;notNull&quot;: true<br>          },<br>          {<br>            &quot;fieldPath&quot;: &quot;name&quot;,<br>            &quot;columnName&quot;: &quot;name&quot;,<br>            &quot;affinity&quot;: &quot;TEXT&quot;,<br>            &quot;notNull&quot;: true<br>          }<br>        ],<br>        &quot;primaryKey&quot;: {<br>          &quot;columnNames&quot;: [&quot;id&quot;],<br>          &quot;autoGenerate&quot;: true<br>        },<br>        &quot;indices&quot;: [],<br>        &quot;foreignKeys&quot;: []<br>      }<br>    ],<br>    &quot;setupQueries&quot;: [<br>      &quot;CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)&quot;,<br>      &quot;INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, &#39;a3f2b8c9d4e5f6a7b8c9d0e1f2a3b4c5&#39;)&quot;<br>    ]<br>  }<br>}</pre><h3>Why Export Schemas?</h3><ol><li><strong>Version Control</strong> — Track schema changes in Git</li><li><strong>Migration Testing</strong> — Test migrations against real schemas</li><li><strong>Code Review</strong> — Review schema changes in PRs</li><li><strong>Auto-Migration</strong> — Required for auto-migrations to work</li><li><strong>Documentation</strong> — Clear history of database evolution</li></ol><h3>Testing Migrations</h3><pre>@RunWith(AndroidJUnit4::class)<br>class MigrationTest {<br><br>      @get:Rule<br>    val helper = MigrationTestHelper(<br>        InstrumentationRegistry.getInstrumentation(),<br>        AppDatabase::class.java,<br>        listOf(),  // Auto-migrations<br>        FrameworkSQLiteOpenHelperFactory()<br>    )<br>    @Test<br>    fun migrate1To2() {<br>        // Create database with version 1<br>        helper.createDatabase(&quot;test-db&quot;, 1).apply {<br>            execSQL(&quot;INSERT INTO users (id, name) VALUES (1, &#39;John&#39;)&quot;)<br>            close()<br>        }<br>        // Run migration and validate<br>        helper.runMigrationsAndValidate(&quot;test-db&quot;, 2, true, MIGRATION_1_2).apply {<br>            val cursor = query(&quot;SELECT * FROM users WHERE id = 1&quot;)<br>            cursor.moveToFirst()<br>            assertEquals(&quot;John&quot;, cursor.getString(cursor.getColumnIndex(&quot;name&quot;)))<br>            assertEquals(&quot;&quot;, cursor.getString(cursor.getColumnIndex(&quot;email&quot;)))  // New column<br>            close()<br>        }<br>    }<br>}</pre><h3>10. Common Pitfalls and Best Practices</h3><h3>Pitfall 1: Forgetting @ColumnInfo Default Values</h3><pre>// ❌ Bad: Migration will fail<br>@Entity<br>data class User(<br>    @PrimaryKey val id: Long,<br>    val name: String,<br>    val age: Int  // New non-null field without default<br>)<br><br>// Migration:<br>db.execSQL(&quot;ALTER TABLE users ADD COLUMN age INTEGER NOT NULL&quot;)<br>// CRASH: NOT NULL constraint requires default value</pre><pre>// ✅ Good: Provide default in SQL<br>db.execSQL(&quot;ALTER TABLE users ADD COLUMN age INTEGER NOT NULL DEFAULT 0&quot;)<br><br>// Or make it nullable in entity<br>@Entity<br>data class User(<br>    @PrimaryKey val id: Long,<br>    val name: String,<br>    val age: Int? = null  // Nullable is OK<br>)</pre><h3>Pitfall 2: SQLite ALTER TABLE Limitations</h3><p>SQLite has limited ALTER TABLE support:</p><pre>// ✅ Supported<br>ALTER TABLE users ADD COLUMN email TEXT<br>ALTER TABLE users RENAME TO customers<br>ALTER TABLE users RENAME COLUMN name TO full_name  // SQLite 3.25+<br><br>// ❌ NOT Supported<br>ALTER TABLE users DROP COLUMN temp_field<br>ALTER TABLE users MODIFY COLUMN name VARCHAR(100)<br>ALTER TABLE users ADD PRIMARY KEY (id)</pre><h3>Workaround: Table Recreation</h3><pre>override fun migrate(db: SupportSQLiteDatabase) {<br>    // 1. Create new table with desired schema<br>    db.execSQL(&quot;&quot;&quot;<br>        CREATE TABLE users_new (<br>            id INTEGER PRIMARY KEY NOT NULL,<br>            name TEXT NOT NULL,<br>            email TEXT NOT NULL<br>            -- &#39;temp_field&#39; is gone (dropped)<br>        )<br>    &quot;&quot;&quot;)<br><br>    // 2. Copy data<br>    db.execSQL(&quot;&quot;&quot;<br>        INSERT INTO users_new (id, name, email)<br>        SELECT id, name, email FROM users<br>    &quot;&quot;&quot;)<br>    // 3. Drop old table<br>    db.execSQL(&quot;DROP TABLE users&quot;)<br>    // 4. Rename new table<br>    db.execSQL(&quot;ALTER TABLE users_new RENAME TO users&quot;)<br>    // 5. Recreate indices<br>    db.execSQL(&quot;CREATE INDEX index_users_email ON users(email)&quot;)<br>}</pre><h3>Pitfall 3: Foreign Key Constraints</h3><pre>// If you have foreign keys, disable checks during migration<br>override fun migrate(db: SupportSQLiteDatabase) {<br>    db.execSQL(&quot;PRAGMA foreign_keys=OFF&quot;)<br><br>    // ... migration logic ...<br>    db.execSQL(&quot;PRAGMA foreign_keys=ON&quot;)<br>    // Validate foreign key integrity<br>    val cursor = db.query(&quot;PRAGMA foreign_key_check&quot;)<br>    if (cursor.count &gt; 0) {<br>        throw IllegalStateException(&quot;Foreign key violation after migration&quot;)<br>    }<br>}</pre><h3>Best Practices Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*Zl5bD_rX1nNdlAVMNzVfiw.png" /><figcaption>Best Practices Summary</figcaption></figure><h3>Conclusion</h3><p>Room’s migration system is designed to protect your users’ data. The schema hash ensures you never accidentally corrupt a database, and the migration system gives you full control over how data evolves.</p><p><strong>Key Takeaways:</strong></p><ol><li><strong>Schema</strong> = Database blueprint (tables, columns, indices)</li><li><strong>Identity Hash</strong> = Unique fingerprint of your schema</li><li><strong>room_master_table</strong> = Stores the hash in the database file</li><li><strong>Crash on mismatch</strong> = Intentional protection, not a bug</li><li><strong>Migration</strong> = Your instructions for evolving the schema</li><li><strong>Destructive fallback</strong> = Nuclear option, destroys all data</li><li><strong>Export schemas</strong> = Version control for your database</li></ol><p>The error message isn’t your enemy — it’s Room protecting your users from data loss. Embrace it, understand it, and your database migrations will be rock solid.</p><h3>Quick Reference Card</h3><pre>// 1. Always set version<br>@Database(entities = [...], version = 2, exportSchema = true)<br><br>// 2. Write migration<br>val MIGRATION_1_2 = object : Migration(1, 2) {<br>    override fun migrate(db: SupportSQLiteDatabase) {<br>        db.execSQL(&quot;ALTER TABLE users ADD COLUMN age INTEGER NOT NULL DEFAULT 0&quot;)<br>    }<br>}<br>// 3. Register migration<br>Room.databaseBuilder(context, AppDatabase::class.java, &quot;app.db&quot;)<br>    .addMigrations(MIGRATION_1_2)<br>    .build()<br>// 4. Test migration<br>@Test<br>fun testMigration1To2() {<br>    helper.createDatabase(&quot;test&quot;, 1)<br>    helper.runMigrationsAndValidate(&quot;test&quot;, 2, true, MIGRATION_1_2)<br>}</pre><p>That’s it. Now you understand Room migrations from the inside out.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca8e3538bf57" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/why-room-crashes-when-you-change-your-database-and-how-to-fix-it-ca8e3538bf57">Why Room Crashes When You Change Your Database (And How to Fix It)</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[HashMap and Set Performance Optimization in Android Kotlin: The Complete Professional Guide]]></title>
            <link>https://medium.com/@doanthanhtungnk123/hashmap-and-set-performance-optimization-in-android-kotlin-the-complete-professional-guide-8657f067372b?source=rss-55f8aed942a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8657f067372b</guid>
            <category><![CDATA[hashmap]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[hashset]]></category>
            <dc:creator><![CDATA[Tung Doan]]></dc:creator>
            <pubDate>Sat, 03 Jan 2026 04:33:41 GMT</pubDate>
            <atom:updated>2026-01-03T04:33:41.747Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XUIP2YAXP5F6H1c5Pgx1yw.png" /></figure><h3>TL;DR — Quick Performance Gains</h3><p><strong>Immediate Optimizations:</strong></p><ul><li>Replace List.contains() with Set.contains() for O(1) lookup instead of O(n)</li><li>Use HashMap for key-value caching instead of List.find()</li><li>Choose ArrayMap for small datasets (&lt; 1000 items) on Android</li><li>Prefer mutableSetOf() over mutableListOf() for uniqueness checks</li><li>Use HashSet constructor with initial capacity when size is known</li></ul><p><strong>Performance Hierarchy (Best to Worst for Lookups):</strong></p><ol><li>HashMap/HashSet: O(1) average case</li><li>ArrayMap/ArraySet: O(log n) — better memory, slower lookup</li><li>LinkedHashMap/LinkedHashSet: O(1) but higher memory overhead</li><li>List: O(n) — avoid for frequent lookups</li></ol><p><strong>Quick Wins:</strong></p><pre>// Bad: O(n) lookup in list<br>val userIds = listOf(&quot;user1&quot;, &quot;user2&quot;, &quot;user3&quot;)<br>if (userId in userIds) { } // Scans entire list<br><br>// Good: O(1) lookup in set<br>val userIds = setOf(&quot;user1&quot;, &quot;user2&quot;, &quot;user3&quot;)<br>if (userId in userIds) { } // Instant lookup</pre><h3>Table of Contents</h3><ol><li>Understanding HashMap and Set Internals</li><li>Performance Characteristics and Big-O Analysis</li><li>Android-Specific Collections: ArrayMap vs HashMap</li><li>Real-World Android Use Cases</li><li>Common Performance Pitfalls</li><li>Advanced Optimization Techniques</li><li>Memory vs Speed Tradeoffs</li><li>Benchmarks and Measurements</li><li>Best Practices Decision Matrix</li><li>Production-Ready Code Examples</li></ol><h3>1. Understanding HashMap and Set Internals</h3><h3>How HashMap Works</h3><p>HashMap in Kotlin/Java uses an array of buckets with linked lists (or trees for high collision scenarios):</p><pre>// Simplified internal structure<br>class HashMap&lt;K, V&gt; {<br>    private var table: Array&lt;Node&lt;K, V&gt;?&gt; = arrayOfNulls(16)<br>    private var size = 0<br>    class Node&lt;K, V&gt;(<br>        val hash: Int,<br>        val key: K,<br>        var value: V,<br>        var next: Node&lt;K, V&gt;? = null<br>    )<br>    fun put(key: K, value: V) {<br>        val hash = key.hashCode()<br>        val index = hash and (table.size - 1) // Modulo via bitwise AND<br>        // Find bucket and insert/update<br>        var node = table[index]<br>        while (node != null) {<br>            if (node.key == key) {<br>                node.value = value // Update existing<br>                return<br>            }<br>            node = node.next<br>        }<br>        // Insert new node at bucket head<br>    }<br>}</pre><p><strong>Key Points:</strong></p><ul><li>Hash function determines bucket placement</li><li>Collisions are handled via chaining (linked list)</li><li>Load factor triggers resize (default 0.75)</li><li>Average case O(1), worst case O(n) with many collisions</li></ul><h3>How HashSet Works</h3><p>HashSet is a HashMap wrapper where values are a dummy object:</p><pre>// Simplified HashSet implementation<br>class HashSet&lt;E&gt; {<br>    private val map = HashMap&lt;E, Any&gt;()<br>    private val PRESENT = Object()<br>    fun add(element: E): Boolean {<br>        return map.put(element, PRESENT) == null<br>    }<br>    fun contains(element: E): Boolean {<br>        return map.containsKey(element)<br>    }<br>}</pre><p><strong>Performance:</strong> Identical to HashMap for lookups and insertions.</p><h3>Hash Function Quality Matters</h3><pre>// Bad hash function - many collisions<br>data class User(val id: Int, val name: String) {<br>    override fun hashCode() = 1 // Everything goes to same bucket!<br>}<br><br>// Good hash function - distributed buckets<br>data class User(val id: Int, val name: String) {<br>    override fun hashCode() = Objects.hash(id, name)<br>}</pre><p>Poor hash functions degrade HashMap from O(1) to O(n).</p><h3>2. Performance Characteristics and Big-O Analysis</h3><h3>Operation Complexity Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*kxA1L0C0zWkr6GjSSsPQ6g.png" /><figcaption>Operation Complexity Comparison</figcaption></figure><ul><li>ArrayList add() is amortized O(1) due to occasional resize</li></ul><h3>Real Performance Numbers (Android Device, 10,000 items)</h3><pre>// Benchmark results (approximate milliseconds)<br>val items = (1..10000).toList()<br><br>// List.contains() - Linear scan<br>repeat(1000) { items.contains(5000) } // ~450ms<br><br>// HashSet.contains() - Hash lookup<br>val set = items.toSet()<br>repeat(1000) { set.contains(5000) } // ~0.5ms<br><br>// HashMap.get() - Hash lookup<br>val map = items.associateWith { it }<br>repeat(1000) { map[5000] } // ~0.5ms<br><br>// ArraySet.contains() - Binary search<br>val arraySet = ArraySet(items)<br>repeat(1000) { arraySet.contains(5000) } // ~5ms</pre><p><strong>900x faster with HashSet vs List for lookups!</strong></p><h3>Memory Consumption Analysis</h3><pre>// Memory overhead per entry (approximate)<br>ArrayList&lt;Int&gt;:     4 bytes (just reference)<br>LinkedList&lt;Int&gt;:    24 bytes (object + 2 pointers)<br>HashSet&lt;Int&gt;:       32 bytes (entry + hash + next pointer)<br>HashMap&lt;Int, Int&gt;:  32 bytes (same as HashSet)<br>ArrayMap&lt;Int, Int&gt;: 8 bytes (2 arrays, packed)<br>ArraySet&lt;Int&gt;:      4 bytes (single array, packed)</pre><h3>3. Android-Specific Collections: ArrayMap vs HashMap</h3><p>More detail please read this <a href="https://medium.com/proandroiddev/optimizing-android-performance-when-to-use-sparsearray-sparseintarray-and-arraymap-instead-of-47e1e9c9f101">article</a>:</p><h3>ArrayMap Internal Structure</h3><pre>// Simplified ArrayMap structure<br>class ArrayMap&lt;K, V&gt; {<br>    private var hashes: IntArray = IntArray(0)<br>    private var array: Array&lt;Any?&gt; = arrayOfNulls(0)<br>    private var size = 0<br>    fun put(key: K, value: V) {<br>        val hash = key.hashCode()<br>        val index = binarySearch(hashes, size, hash)<br>        if (index &gt;= 0) {<br>            array[index shl 1 + 1] = value // Update<br>        } else {<br>            val insertIndex = index.inv()<br>            // Insert at sorted position<br>            hashes = hashes.insert(insertIndex, hash)<br>            array = array.insert(insertIndex shl 1, key, value)<br>        }<br>    }<br>}</pre><p><strong>Key Differences from HashMap:</strong></p><ul><li>Uses two arrays instead of array of nodes</li><li>Binary search instead of hash bucket lookup</li><li>Lower memory overhead (no Node objects)</li><li>Slower for large datasets (log n vs constant time)</li></ul><h3>When to Use ArrayMap vs HashMap</h3><p><strong>Use ArrayMap when:</strong></p><ul><li>Dataset size &lt; 1000 items</li><li>Memory is more critical than speed</li><li>Frequent iteration (better cache locality)</li><li>Android framework classes (Bundle, Intent extras)</li></ul><p><strong>Use HashMap when:</strong></p><ul><li>Dataset size &gt; 1000 items</li><li>Lookup speed is critical</li><li>High frequency of operations (thousands per second)</li><li>Standard JVM compatibility needed</li></ul><h3>Performance Crossover Point</h3><pre>// Benchmark: Operations per second<br>fun benchmarkCollections(size: Int) {<br>    val hashMap = HashMap&lt;Int, String&gt;(size)<br>    val arrayMap = ArrayMap&lt;Int, String&gt;(size)<br>    // Populate<br>    repeat(size) {<br>        hashMap[it] = &quot;value$it&quot;<br>        arrayMap[it] = &quot;value$it&quot;<br>    }<br>    // Measure lookups<br>    measureTimeMillis {<br>        repeat(10000) { hashMap[size / 2] }<br>    }.also { println(&quot;HashMap($size): ${it}ms&quot;) }<br>    measureTimeMillis {<br>        repeat(10000) { arrayMap[size / 2] }<br>    }.also { println(&quot;ArrayMap($size): ${it}ms&quot;) }<br>}<br>// Results:<br>// HashMap(100): 2ms, ArrayMap(100): 3ms<br>// HashMap(1000): 2ms, ArrayMap(1000): 12ms<br>// HashMap(10000): 2ms, ArrayMap(10000): 85ms</pre><p><strong>Crossover point: ~500–1000 items</strong></p><h3>4. Real-World Android Use Cases</h3><h3>4.1 Caching Network Responses</h3><p><strong>Problem:</strong> Repeatedly fetching same data from API</p><p><strong>Bad Approach (List):</strong></p><pre>class UserRepository {<br>    private val cachedUsers = mutableListOf&lt;User&gt;()<br>    suspend fun getUser(id: String): User {<br>        // O(n) search every time!<br>        val cached = cachedUsers.find { it.id == id }<br>        if (cached != null) return cached<br>        val user = api.fetchUser(id)<br>        cachedUsers.add(user)<br>        return user<br>    }<br>}</pre><p><strong>Good Approach (HashMap):</strong></p><pre>class UserRepository {<br>    private val cachedUsers = mutableMapOf&lt;String, User&gt;()<br><br>    suspend fun getUser(id: String): User {<br>        // O(1) lookup!<br>        return cachedUsers.getOrPut(id) {<br>            api.fetchUser(id)<br>        }<br>    }<br>    fun invalidateCache(id: String) {<br>        cachedUsers.remove(id)<br>    }<br>    fun clearCache() {<br>        cachedUsers.clear()<br>    }<br>}</pre><p>Performance Impact:</p><ul><li>List approach: 50ms for 1000 cached users</li><li>HashMap approach: 0.05ms (1000x faster)</li></ul><h3>4.2 RecyclerView Item Lookup</h3><p><strong>Problem:</strong> Finding items by ID in adapter</p><p><strong>Bad Approach:</strong></p><pre>class UserAdapter : RecyclerView.Adapter&lt;UserViewHolder&gt;() {<br>    private val users = mutableListOf&lt;User&gt;()<br><br>    fun updateUser(updatedUser: User) {<br>        val position = users.indexOfFirst { it.id == updatedUser.id }<br>        if (position &gt;= 0) {<br>            users[position] = updatedUser<br>            notifyItemChanged(position)<br>        }<br>    }<br>}</pre><p><strong>Good Approach:</strong></p><pre>class UserAdapter : RecyclerView.Adapter&lt;UserViewHolder&gt;() {<br>    private val users = mutableListOf&lt;User&gt;()<br>    private val userPositions = mutableMapOf&lt;String, Int&gt;()<br><br>    fun setUsers(newUsers: List&lt;User&gt;) {<br>        users.clear()<br>        userPositions.clear()<br>        users.addAll(newUsers)<br>        newUsers.forEachIndexed { index, user -&gt;<br>            userPositions[user.id] = index<br>        }<br>        notifyDataSetChanged()<br>    }<br>    fun updateUser(updatedUser: User) {<br>        val position = userPositions[updatedUser.id] ?: return<br>        users[position] = updatedUser<br>        notifyItemChanged(position)<br>    }<br>    override fun getItemCount() = users.size<br>    override fun onBindViewHolder(holder: UserViewHolder, position: Int) {<br>        holder.bind(users[position])<br>    }<br>}</pre><h3>4.3 Deduplication in Real-Time Streams</h3><p><strong>Problem:</strong> Removing duplicates from WebSocket or Flow emissions</p><p><strong>Bad Approach:</strong></p><pre>class EventProcessor {<br>    private val processedIds = mutableListOf&lt;String&gt;()<br><br>    fun processEvent(event: Event) {<br>        if (processedIds.contains(event.id)) return // O(n) check<br>        processedIds.add(event.id)<br>        handleEvent(event)<br>    }<br>}</pre><p><strong>Good Approach:</strong></p><pre>class EventProcessor {<br>    private val processedIds = mutableSetOf&lt;String&gt;()<br><br>    fun processEvent(event: Event) {<br>        if (!processedIds.add(event.id)) return // O(1) check + add<br>        handleEvent(event)<br>    }<br>    fun clearProcessedEvents() {<br>        processedIds.clear()<br>    }<br>}<br>// With Flow<br>fun &lt;T&gt; Flow&lt;T&gt;.distinctByIdWithSet(<br>    getId: (T) -&gt; String<br>): Flow&lt;T&gt; = flow {<br>    val seen = mutableSetOf&lt;String&gt;()<br>    collect { value -&gt;<br>        if (seen.add(getId(value))) {<br>            emit(value)<br>        }<br>    }<br>}<br>// Usage<br>eventFlow<br>    .distinctByIdWithSet { it.id }<br>    .collect { processEvent(it) }</pre><h3>4.4 Permission Checking</h3><p><strong>Bad Approach:</strong></p><pre>class PermissionManager {<br>    private val grantedPermissions = listOf(<br>        Manifest.permission.CAMERA,<br>        Manifest.permission.LOCATION,<br>        Manifest.permission.STORAGE<br>    )<br><br>    fun hasPermission(permission: String): Boolean {<br>        return grantedPermissions.contains(permission) // O(n)<br>    }<br>}</pre><p><strong>Good Approach:</strong></p><pre>class PermissionManager(context: Context) {<br>    private val grantedPermissions = mutableSetOf&lt;String&gt;()<br><br>    init {<br>        updateGrantedPermissions(context)<br>    }<br>    private fun updateGrantedPermissions(context: Context) {<br>        grantedPermissions.clear()<br>        val allPermissions = listOf(<br>            Manifest.permission.CAMERA,<br>            Manifest.permission.READ_CONTACTS,<br>            Manifest.permission.ACCESS_FINE_LOCATION<br>        )<br>        allPermissions.forEach { permission -&gt;<br>            if (ContextCompat.checkSelfPermission(context, permission)<br>                == PackageManager.PERMISSION_GRANTED) {<br>                grantedPermissions.add(permission)<br>            }<br>        }<br>    }<br>    fun hasPermission(permission: String): Boolean {<br>        return permission in grantedPermissions // O(1)<br>    }<br>    fun hasAllPermissions(permissions: Set&lt;String&gt;): Boolean {<br>        return grantedPermissions.containsAll(permissions)<br>    }<br>}</pre><h3>4.5 Database Query Result Mapping</h3><p><strong>Problem:</strong> Converting list of IDs to objects efficiently</p><p><strong>Bad Approach:</strong></p><pre>class PostRepository {<br>    suspend fun getPostsWithAuthors(postIds: List&lt;String&gt;): List&lt;PostWithAuthor&gt; {<br>        val posts = database.getPosts(postIds)<br>        val authors = database.getAllAuthors()<br>        return posts.map { post -&gt;<br>            // O(n) search for each post!<br>            val author = authors.find { it.id == post.authorId }<br>            PostWithAuthor(post, author)<br>        }<br>    }<br>}</pre><p><strong>Good Approach:</strong></p><pre>class PostRepository {<br>    suspend fun getPostsWithAuthors(postIds: List&lt;String&gt;): List&lt;PostWithAuthor&gt; {<br>        val posts = database.getPosts(postIds)<br>        val authorIds = posts.map { it.authorId }.toSet()<br>        val authors = database.getAuthors(authorIds.toList())<br><br>        // Build lookup map O(n)<br>        val authorMap = authors.associateBy { it.id }<br>        // Map with O(1) lookups<br>        return posts.map { post -&gt;<br>            val author = authorMap[post.authorId]<br>            PostWithAuthor(post, author)<br>        }<br>    }<br>}</pre><p><strong>Performance Impact:</strong></p><ul><li>1000 posts, 100 authors</li><li>Bad: ~100ms (1000 × 100 comparisons)</li><li>Good: ~2ms (1000 + 100 + 1000 operations)</li></ul><h3>4.6 Jetpack Compose State Management</h3><p><strong>Problem:</strong> Tracking selected items in LazyList</p><p><strong>Bad Approach:</strong></p><pre>@Composable<br>fun SelectableList(items: List&lt;Item&gt;) {<br>    var selectedIds by remember { mutableStateOf(listOf&lt;String&gt;()) }<br><br>    LazyColumn {<br>        items(items) { item -&gt;<br>            val isSelected = selectedIds.contains(item.id) // O(n) every recomposition!<br>            ItemRow(<br>                item = item,<br>                isSelected = isSelected,<br>                onClick = {<br>                    selectedIds = if (isSelected) {<br>                        selectedIds - item.id<br>                    } else {<br>                        selectedIds + item.id<br>                    }<br>                }<br>            )<br>        }<br>    }<br>}</pre><p><strong>Good Approach:</strong></p><pre>@Composable<br>fun SelectableList(items: List&lt;Item&gt;) {<br>    var selectedIds by remember { mutableStateOf(setOf&lt;String&gt;()) }<br>    LazyColumn {<br>        items(<br>            items = items,<br>            key = { it.id }<br>        ) { item -&gt;<br>            val isSelected = item.id in selectedIds // O(1)<br>            ItemRow(<br>                item = item,<br>                isSelected = isSelected,<br>                onClick = {<br>                    selectedIds = if (isSelected) {<br>                        selectedIds - item.id<br>                    } else {<br>                        selectedIds + item.id<br>                    }<br>                }<br>            )<br>        }<br>    }<br>}<br>// Even better with state class<br>@Stable<br>class SelectionState {<br>    private val _selectedIds = mutableStateOf(setOf&lt;String&gt;())<br>    val selectedIds: Set&lt;String&gt; get() = _selectedIds.value<br>    fun toggle(id: String) {<br>        _selectedIds.value = if (id in _selectedIds.value) {<br>            _selectedIds.value - id<br>        } else {<br>            _selectedIds.value + id<br>        }<br>    }<br>    fun isSelected(id: String) = id in _selectedIds.value<br>    fun selectAll(ids: Set&lt;String&gt;) {<br>        _selectedIds.value = ids<br>    }<br>    fun clearSelection() {<br>        _selectedIds.value = emptySet()<br>    }<br>}</pre><h3>5. Common Performance Pitfalls</h3><h3>5.1 Using List for Membership Testing</h3><p><strong>Problem:</strong></p><pre>class ContentFilter {<br>    private val blockedWords = listOf(&quot;spam&quot;, &quot;abuse&quot;, &quot;scam&quot;)<br><br>    fun isBlocked(text: String): Boolean {<br>        return text.split(&quot; &quot;).any { word -&gt;<br>            blockedWords.contains(word.lowercase()) // O(n) per word!<br>        }<br>    }<br>}</pre><p><strong>Solution:</strong></p><pre>class ContentFilter {<br>    private val blockedWords = setOf(&quot;spam&quot;, &quot;abuse&quot;, &quot;scam&quot;)<br><br>    fun isBlocked(text: String): Boolean {<br>        return text.split(&quot; &quot;).any { word -&gt;<br>            word.lowercase() in blockedWords // O(1) per word<br>        }<br>    }<br>}</pre><h3>5.2 Rebuilding HashMap on Every Access</h3><p><strong>Problem:</strong></p><pre>class UserViewModel : ViewModel() {<br>    val users = MutableStateFlow&lt;List&lt;User&gt;&gt;(emptyList())</pre><pre>    fun getUserById(id: String): User? {<br>        // Rebuilds map every call!<br>        return users.value.associateBy { it.id }[id]<br>    }<br>}</pre><p><strong>Solution:</strong></p><pre>class UserViewModel : ViewModel() {<br>    private val _users = MutableStateFlow&lt;List&lt;User&gt;&gt;(emptyList())<br>    val users = _users.asStateFlow()</pre><pre>    private val userMap = mutableMapOf&lt;String, User&gt;()</pre><pre>    fun setUsers(newUsers: List&lt;User&gt;) {<br>        _users.value = newUsers<br>        userMap.clear()<br>        newUsers.associateByTo(userMap) { it.id }<br>    }</pre><pre>    fun getUserById(id: String): User? = userMap[id]<br>}</pre><h3>5.3 Not Sizing Collections Properly</h3><p><strong>Problem:</strong></p><pre>fun processLargeDataset(items: List&lt;Item&gt;) {<br>    val resultMap = mutableMapOf&lt;String, Result&gt;()</pre><pre>    items.forEach { item -&gt;<br>        resultMap[item.id] = process(item)<br>        // Triggers multiple resizes as map grows<br>    }<br>}</pre><p><strong>Solution:</strong></p><pre>fun processLargeDataset(items: List&lt;Item&gt;) {<br>    // Pre-size to avoid resizes<br>    val resultMap = HashMap&lt;String, Result&gt;(items.size)<br>    items.forEach { item -&gt;<br>        resultMap[item.id] = process(item)<br>    }<br>}</pre><p><strong>Performance Impact:</strong> 10–20% faster with pre-sizing for large datasets.</p><h3>5.4 Using HashMap Where ArrayMap is Better</h3><p><strong>Problem:</strong></p><pre>class ViewHolder(view: View) {<br>    // Small dataset, high memory overhead<br>    private val viewCache = HashMap&lt;Int, View&gt;()<br>    fun cacheView(id: Int, view: View) {<br>        viewCache[id] = view<br>    }<br>}</pre><p><strong>Solution:</strong></p><pre>class ViewHolder(view: View) {<br>    // Better for small datasets<br>    private val viewCache = ArrayMap&lt;Int, View&gt;()<br><br>    fun cacheView(id: Int, view: View) {<br>        viewCache[id] = view<br>    }<br>}</pre><h3>5.5 Ignoring Hash Function Quality</h3><p><strong>Problem:</strong></p><pre>data class CacheKey(<br>    val userId: String,<br>    val timestamp: Long,<br>    val type: String<br>) {<br>    // Poor hash distribution<br>    override fun hashCode() = userId.hashCode()<br>}</pre><p><strong>Solution:</strong></p><pre>data class CacheKey(<br>    val userId: String,<br>    val timestamp: Long,<br>    val type: String<br>) {<br>    // Good hash distribution<br>    override fun hashCode(): Int {<br>        var result = userId.hashCode()<br>        result = 31 * result + timestamp.hashCode()<br>        result = 31 * result + type.hashCode()<br>        return result<br>    }<br>}<br><br>// Or use Kotlin&#39;s data class default (already optimized)</pre><h3>6. Advanced Optimization Techniques</h3><h3>6.1 LRU Cache with LinkedHashMap</h3><pre>class LruCache&lt;K, V&gt;(private val maxSize: Int) {<br>    private val cache = object : LinkedHashMap&lt;K, V&gt;(<br>        maxSize + 1,<br>        0.75f,<br>        true // Access order (LRU)<br>    ) {<br>        override fun removeEldestEntry(eldest: Map.Entry&lt;K, V&gt;): Boolean {<br>            return size &gt; maxSize<br>        }<br>    }<br>    operator fun get(key: K): V? = synchronized(cache) {<br>        cache[key]<br>    }<br>    operator fun set(key: K, value: V) = synchronized(cache) {<br>        cache[key] = value<br>    }<br>}<br><br>// Usage in repository<br>class ImageRepository {<br>    private val imageCache = LruCache&lt;String, Bitmap&gt;(50)<br>    suspend fun getImage(url: String): Bitmap {<br>        imageCache[url]?.let { return it }<br>        val bitmap = downloadImage(url)<br>        imageCache[url] = bitmap<br>        return bitmap<br>    }<br>}</pre><h3>6.2 Multimap Pattern with HashMap</h3><pre>class Multimap&lt;K, V&gt; {<br>    private val map = mutableMapOf&lt;K, MutableSet&lt;V&gt;&gt;()<br>    fun put(key: K, value: V) {<br>        map.getOrPut(key) { mutableSetOf() }.add(value)<br>    }<br>    fun get(key: K): Set&lt;V&gt; = map[key] ?: emptySet()<br>    fun remove(key: K, value: V): Boolean {<br>        return map[key]?.remove(value) ?: false<br>    }<br>    fun removeAll(key: K): Set&lt;V&gt;? = map.remove(key)<br>}<br><br>// Real-world usage: Tag-based filtering<br>class ArticleRepository {<br>    private val articlesByTag = Multimap&lt;String, Article&gt;()<br>    fun indexArticle(article: Article) {<br>        article.tags.forEach { tag -&gt;<br>            articlesByTag.put(tag, article)<br>        }<br>    }<br>    fun getArticlesByTag(tag: String): Set&lt;Article&gt; {<br>        return articlesByTag.get(tag)<br>    }<br>    fun getArticlesByTags(tags: Set&lt;String&gt;): Set&lt;Article&gt; {<br>        return tags.flatMap { articlesByTag.get(it) }.toSet()<br>    }<br>}</pre><h3>6.3 Bidirectional Map</h3><pre>class BiMap&lt;K, V&gt; {<br>    private val keyToValue = mutableMapOf&lt;K, V&gt;()<br>    private val valueToKey = mutableMapOf&lt;V, K&gt;()<br><br>    fun put(key: K, value: V) {<br>        keyToValue[key]?.let { oldValue -&gt;<br>            valueToKey.remove(oldValue)<br>        }<br>        valueToKey[value]?.let { oldKey -&gt;<br>            keyToValue.remove(oldKey)<br>        }<br>        keyToValue[key] = value<br>        valueToKey[value] = key<br>    }<br>    fun getByKey(key: K): V? = keyToValue[key]<br>    fun getByValue(value: V): K? = valueToKey[value]<br>    fun removeByKey(key: K): V? {<br>        val value = keyToValue.remove(key)<br>        value?.let { valueToKey.remove(it) }<br>        return value<br>    }<br>}<br>// Usage: User ID &lt;-&gt; Session mapping<br>class SessionManager {<br>    private val sessions = BiMap&lt;String, String&gt;() // userId &lt;-&gt; sessionId<br>    fun createSession(userId: String, sessionId: String) {<br>        sessions.put(userId, sessionId)<br>    }<br>    fun getUserBySession(sessionId: String): String? {<br>        return sessions.getByValue(sessionId)<br>    }<br>    fun getSessionByUser(userId: String): String? {<br>        return sessions.getByKey(userId)<br>    }<br>}</pre><h3>6.4 Counting with HashMap</h3><pre>class FrequencyCounter&lt;T&gt; {<br>    private val counts = mutableMapOf&lt;T, Int&gt;()<br>    fun increment(item: T) {<br>        counts[item] = (counts[item] ?: 0) + 1<br>    }<br>    fun getCount(item: T): Int = counts[item] ?: 0<br>    fun getMostFrequent(n: Int): List&lt;Pair&lt;T, Int&gt;&gt; {<br>        return counts.entries<br>            .sortedByDescending { it.value }<br>            .take(n)<br>            .map { it.key to it.value }<br>    }<br>}<br>// Analytics usage<br>class EventAnalytics {<br>    private val eventCounts = FrequencyCounter&lt;String&gt;()<br>    fun trackEvent(eventName: String) {<br>        eventCounts.increment(eventName)<br>    }<br>    fun getTopEvents(limit: Int = 10): List&lt;Pair&lt;String, Int&gt;&gt; {<br>        return eventCounts.getMostFrequent(limit)<br>    }<br>}</pre><h3>6.5 Grouping with HashMap</h3><pre>// Built-in groupBy allocates intermediate lists<br>fun &lt;T, K&gt; List&lt;T&gt;.efficientGroupBy(<br>    keySelector: (T) -&gt; K<br>): Map&lt;K, List&lt;T&gt;&gt; {<br>    val result = mutableMapOf&lt;K, MutableList&lt;T&gt;&gt;()<br>    for (element in this) {<br>        val key = keySelector(element)<br>        result.getOrPut(key) { mutableListOf() }.add(element)<br>    }<br>    return result<br>}<br><br>// Usage: Group users by age range<br>data class User(val name: String, val age: Int)<br>fun groupUsersByAgeRange(users: List&lt;User&gt;): Map&lt;String, List&lt;User&gt;&gt; {<br>    return users.efficientGroupBy { user -&gt;<br>        when (user.age) {<br>            in 0..17 -&gt; &quot;Minor&quot;<br>            in 18..35 -&gt; &quot;Young Adult&quot;<br>            in 36..60 -&gt; &quot;Adult&quot;<br>            else -&gt; &quot;Senior&quot;<br>        }<br>    }<br>}</pre><h3>6.6 Two-Level Caching</h3><pre>class TwoLevelCache&lt;K, V&gt;(<br>    private val memorySize: Int,<br>    private val diskSize: Int<br>) {<br>    private val memoryCache = LruCache&lt;K, V&gt;(memorySize)<br>    private val diskCache = mutableMapOf&lt;K, V&gt;()<br>    private val accessOrder = LinkedHashSet&lt;K&gt;()<br><br>    operator fun get(key: K): V? {<br>        // Check memory first<br>        memoryCache[key]?.let {<br>            return it<br>        }<br>        // Check disk cache<br>        return diskCache[key]?.also {<br>            memoryCache[key] = it<br>            updateAccessOrder(key)<br>        }<br>    }<br>    operator fun set(key: K, value: V) {<br>        memoryCache[key] = value<br>        diskCache[key] = value<br>        updateAccessOrder(key)<br>        // Evict from disk if needed<br>        if (accessOrder.size &gt; diskSize) {<br>            val oldest = accessOrder.first()<br>            accessOrder.remove(oldest)<br>            diskCache.remove(oldest)<br>        }<br>    }<br>    private fun updateAccessOrder(key: K) {<br>        accessOrder.remove(key)<br>        accessOrder.add(key)<br>    }<br>}</pre><h3>7. Memory vs Speed Tradeoffs</h3><h3>Memory Overhead Comparison</h3><pre>// Test with 10,000 integer entries<br>fun measureMemoryOverhead() {<br>    val runtime = Runtime.getRuntime()<br><br>    fun measureCollection(name: String, create: () -&gt; Any) {<br>        runtime.gc()<br>        val before = runtime.totalMemory() - runtime.freeMemory()<br>        val collection = create()<br>        runtime.gc()<br>        val after = runtime.totalMemory() - runtime.freeMemory()<br>        println(&quot;$name: ${(after - before) / 1024}KB&quot;)<br>    }<br>    measureCollection(&quot;ArrayList&quot;) {<br>        ArrayList&lt;Int&gt;(10000).apply {<br>            repeat(10000) { add(it) }<br>        }<br>    }<br>    measureCollection(&quot;HashSet&quot;) {<br>        HashSet&lt;Int&gt;(10000).apply {<br>            repeat(10000) { add(it) }<br>        }<br>    }<br>    measureCollection(&quot;HashMap&quot;) {<br>        HashMap&lt;Int, Int&gt;(10000).apply {<br>            repeat(10000) { put(it, it) }<br>        }<br>    }<br>    measureCollection(&quot;ArraySet&quot;) {<br>        ArraySet&lt;Int&gt;().apply {<br>            repeat(10000) { add(it) }<br>        }<br>    }<br>}<br>// Results (approximate):<br>// ArrayList: 40KB<br>// HashSet: 320KB (8x more)<br>// HashMap: 640KB (16x more)<br>// ArraySet: 80KB (2x more)</pre><h3>Decision Matrix: Memory vs Speed</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*_Xx_AlJEZMEGtew9nQAvjw.png" /><figcaption>Decision Matrix for Hash: Memory vs Speed</figcaption></figure><h3>Choosing Based on Size</h3><pre>// Factory function to choose optimal collection<br>fun &lt;T&gt; createOptimalSet(expectedSize: Int): MutableSet&lt;T&gt; {<br>    return when {<br>        expectedSize &lt; 100 -&gt; ArraySet()<br>        expectedSize &lt; 10000 -&gt; HashSet(expectedSize)<br>        else -&gt; HashSet(expectedSize, 0.75f) // Custom load factor<br>    }<br>}<br><br>fun &lt;K, V&gt; createOptimalMap(expectedSize: Int): MutableMap&lt;K, V&gt; {<br>    return when {<br>        expectedSize &lt; 100 -&gt; ArrayMap()<br>        expectedSize &lt; 10000 -&gt; HashMap(expectedSize)<br>        else -&gt; HashMap(expectedSize, 0.75f)<br>    }<br>}</pre><h3>8. Benchmarks and Measurements</h3><h3>Comprehensive Performance Test</h3><pre>class CollectionBenchmark {<br>    private val sizes = listOf(10, 100, 1000, 10000)<br>    fun runAllBenchmarks() {<br>        sizes.forEach { size -&gt;<br>            println(&quot;\\n=== Size: $size ===&quot;)<br>            benchmarkLookup(size)<br>            benchmarkInsertion(size)<br>            benchmarkIteration(size)<br>        }<br>    }<br>    private fun benchmarkLookup(size: Int) {<br>        val list = (1..size).toList()<br>        val set = list.toSet()<br>        val map = list.associateWith { it * 2 }<br>        val arraySet = ArraySet(list)<br>        val arrayMap = ArrayMap&lt;Int, Int&gt;().apply {<br>            list.forEach { put(it, it * 2) }<br>        }<br>        val iterations = 10000<br>        val searchKey = size / 2<br>        println(&quot;Lookup Performance:&quot;)<br>        measureTimeMillis {<br>            repeat(iterations) { list.contains(searchKey) }<br>        }.also { println(&quot;  List: ${it}ms&quot;) }<br>        measureTimeMillis {<br>            repeat(iterations) { set.contains(searchKey) }<br>        }.also { println(&quot;  HashSet: ${it}ms&quot;) }<br>        measureTimeMillis {<br>            repeat(iterations) { map.containsKey(searchKey) }<br>        }.also { println(&quot;  HashMap: ${it}ms&quot;) }<br>        measureTimeMillis {<br>            repeat(iterations) { arraySet.contains(searchKey) }<br>        }.also { println(&quot;  ArraySet: ${it}ms&quot;) }<br>        measureTimeMillis {<br>            repeat(iterations) { arrayMap.containsKey(searchKey) }<br>        }.also { println(&quot;  ArrayMap: ${it}ms&quot;) }<br>    }<br>    private fun benchmarkInsertion(size: Int) {<br>        println(&quot;Insertion Performance:&quot;)<br>        measureTimeMillis {<br>            val list = mutableListOf&lt;Int&gt;()<br>            repeat(size) { list.add(it) }<br>        }.also { println(&quot;  ArrayList: ${it}ms&quot;) }<br>        measureTimeMillis {<br>            val set = mutableSetOf&lt;Int&gt;()<br>            repeat(size) { set.add(it) }<br>        }.also { println(&quot;  HashSet: ${it}ms&quot;) }<br>        measureTimeMillis {<br>            val map = mutableMapOf&lt;Int, Int&gt;()<br>            repeat(size) { map[it] = it * 2 }<br>        }.also { println(&quot;  HashMap: ${it}ms&quot;) }<br>        measureTimeMillis {<br>            val arraySet = ArraySet&lt;Int&gt;()<br>            repeat(size) { arraySet.add(it) }<br>        }.also { println(&quot;  ArraySet: ${it}ms&quot;) }<br>        measureTimeMillis {<br>            val arrayMap = ArrayMap&lt;Int, Int&gt;()<br>            repeat(size) { arrayMap[it] = it * 2 }<br>        }.also { println(&quot;  ArrayMap: ${it}ms&quot;) }<br>    }<br>    private fun benchmarkIteration(size: Int) {<br>        val list = (1..size).toList()<br>        val set = list.toSet()<br>        val map = list.associateWith { it * 2 }<br>        println(&quot;Iteration Performance:&quot;)<br>        var sum = 0<br>        measureTimeMillis {<br>            list.forEach { sum += it }<br>        }.also { println(&quot;  List: ${it}ms&quot;) }<br>        sum = 0<br>        measureTimeMillis {<br>            set.forEach { sum += it }<br>        }.also { println(&quot;  HashSet: ${it}ms&quot;) }<br>        sum = 0<br>        measureTimeMillis {<br>            map.forEach { sum += it.key }<br>        }.also { println(&quot;  HashMap: ${it}ms&quot;) }<br>    }<br>}<br>// Sample Results on mid-range Android device:<br>// === Size: 1000 ===<br>// Lookup Performance:<br>//   List: 245ms<br>//   HashSet: 1ms<br>//   HashMap: 1ms<br>//   ArraySet: 8ms<br>//   ArrayMap: 8ms</pre><h3>Real-World App Profiling</h3><pre>class PerformanceProfiler {<br>    fun profileUserCache() {<br>        val userIds = (1..5000).map { &quot;user_$it&quot; }<br>        // Test List-based cache<br>        println(&quot;Testing List-based cache...&quot;)<br>        val listCache = mutableListOf&lt;User&gt;()<br>        measureTimeMillis {<br>            userIds.forEach { id -&gt;<br>                val user = listCache.find { it.id == id }<br>                if (user == null) {<br>                    listCache.add(User(id, &quot;Name $id&quot;))<br>                }<br>            }<br>        }.also { println(&quot;List cache build: ${it}ms&quot;) }<br>        measureTimeMillis {<br>            repeat(1000) {<br>                listCache.find { it.id == &quot;user_2500&quot; }<br>            }<br>        }.also { println(&quot;List cache lookup (1000x): ${it}ms&quot;) }<br>        // Test HashMap-based cache<br>        println(&quot;\\nTesting HashMap-based cache...&quot;)<br>        val mapCache = mutableMapOf&lt;String, User&gt;()<br>        measureTimeMillis {<br>            userIds.forEach { id -&gt;<br>                mapCache.getOrPut(id) {<br>                    User(id, &quot;Name $id&quot;)<br>                }<br>            }<br>        }.also { println(&quot;HashMap cache build: ${it}ms&quot;) }<br>        measureTimeMillis {<br>            repeat(1000) {<br>                mapCache[&quot;user_2500&quot;]<br>            }<br>        }.also { println(&quot;HashMap cache lookup (1000x): ${it}ms&quot;) }<br>    }<br>}<br>// Results:<br>// List cache build: 8500ms<br>// List cache lookup (1000x): 2400ms<br>// HashMap cache build: 12ms<br>// HashMap cache lookup (1000x): 0.3ms</pre><h3>9. Best Practices Decision Matrix</h3><h3>Quick Decision Tree</h3><pre>Need to store unique items?<br>├─ Yes<br>│  ├─ Need fast lookup? → HashSet (if &gt; 1000 items)<br>│  ├─ Need memory efficiency? → ArraySet (if &lt; 1000 items)<br>│  └─ Need insertion order? → LinkedHashSet<br>└─ No<br>   └─ Need sequential access only? → ArrayList<br><br>Need key-value pairs?<br>├─ Fast lookup critical? → HashMap (if &gt; 1000 items)<br>├─ Memory critical? → ArrayMap (if &lt; 1000 items)<br>├─ Need insertion order? → LinkedHashMap<br>└─ Need sorted keys? → TreeMap</pre><h3>Use Case Recommendations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*diuf8YWHDnxGfG_yDQNGXw.png" /><figcaption>Use Case Recommendations</figcaption></figure><h3>When to Use HashMap &amp; Set</h3><h3>HashMap</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*9g3Q4TLKCOU-y1rGUM63tw.png" /><figcaption>When to Use HashMap</figcaption></figure><h3>HashSet</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*1VEN3rGiCYVfi40-PPPI1g.png" /><figcaption>When to Use HashSet</figcaption></figure><p>Quick Reference</p><pre>// Load from DB → Cache with HashMap<br>val userCache = mutableMapOf&lt;String, User&gt;()<br>userCache[user.id] = user<br><br>// Check if exists → Use HashSet<br>val likedPosts = mutableSetOf&lt;String&gt;()<br>if (postId in likedPosts) { }<br>// Find by ID → Use HashMap<br>val product = productCache[productId]<br>// Track what&#39;s done → Use HashSet<br>val readMessages = mutableSetOf&lt;String&gt;()<br>readMessages.add(messageId)<br>// Count things → Use HashMap<br>val cartQuantities = mutableMapOf&lt;String, Int&gt;()<br>cartQuantities[productId] = (cartQuantities[productId] ?: 0) + 1</pre><h3>Android-Specific Guidelines</h3><p><strong>Use ArrayMap/ArraySet when:</strong></p><pre>// Bundle extras (small data)<br>class IntentHelper {<br>    fun createIntent(context: Context, extras: Map&lt;String, Any&gt;): Intent {<br>        return Intent(context, Activity::class.java).apply {<br>            val bundle = Bundle()<br>            extras.forEach { (key, value) -&gt;<br>                // ArrayMap internally used by Bundle<br>                when (value) {<br>                    is String -&gt; bundle.putString(key, value)<br>                    is Int -&gt; bundle.putInt(key, value)<br>                }<br>            }<br>            putExtras(bundle)<br>        }<br>    }<br>}<br><br>// View tags (very small data)<br>fun View.setTags(tags: Map&lt;Int, Any&gt;) {<br>    val tagMap = ArrayMap&lt;Int, Any&gt;()<br>    tags.forEach { (key, value) -&gt;<br>        tagMap[key] = value<br>    }<br>}</pre><p><strong>Use HashMap/HashSet when:</strong></p><pre>// Large caches<br>class ImageCache {<br>    private val cache = HashMap&lt;String, Bitmap&gt;(1000)<br><br>    fun get(url: String): Bitmap? = cache[url]<br>    fun put(url: String, bitmap: Bitmap) {<br>        cache[url] = bitmap<br>    }<br>}<br>// Frequent lookups<br>class NavigationManager {<br>    private val routes = HashSet&lt;String&gt;()<br>    fun registerRoute(route: String) {<br>        routes.add(route)<br>    }<br>    fun isValidRoute(route: String): Boolean {<br>        return route in routes<br>    }<br>}</pre><h3>10. Production-Ready Code Examples</h3><h3>10.1 Complete Repository with Caching</h3><pre>class ProductRepository(<br>    private val api: ProductApi,<br>    private val database: ProductDao<br>) {<br>    // HashMap for fast lookups<br>    private val productCache = HashMap&lt;String, Product&gt;(500)<br>    private val categoryCache = HashMap&lt;String, List&lt;Product&gt;&gt;(50)<br>    // HashSet for tracking<br>    private val favoriteIds = HashSet&lt;String&gt;(100)<br>    suspend fun getProduct(id: String): Result&lt;Product&gt; {<br>        // Check cache first<br>        productCache[id]?.let { return Result.success(it) }<br>        // Check database<br>        database.getProduct(id)?.let { product -&gt;<br>            productCache[id] = product<br>            return Result.success(product)<br>        }<br>        // Fetch from API<br>        return try {<br>            val product = api.fetchProduct(id)<br>            productCache[id] = product<br>            database.insertProduct(product)<br>            Result.success(product)<br>        } catch (e: Exception) {<br>            Result.failure(e)<br>        }<br>    }<br>    suspend fun getProductsByCategory(category: String): Result&lt;List&lt;Product&gt;&gt; {<br>        // Check cache<br>        categoryCache[category]?.let { return Result.success(it) }<br>        return try {<br>            val products = api.fetchProductsByCategory(category)<br>            // Update both caches<br>            categoryCache[category] = products<br>            products.forEach { product -&gt;<br>                productCache[product.id] = product<br>            }<br>            Result.success(products)<br>        } catch (e: Exception) {<br>            Result.failure(e)<br>        }<br>    }<br>    fun toggleFavorite(productId: String) {<br>        if (favoriteIds.contains(productId)) {<br>            favoriteIds.remove(productId)<br>        } else {<br>            favoriteIds.add(productId)<br>        }<br>    }<br>    fun isFavorite(productId: String): Boolean {<br>        return productId in favoriteIds<br>    }<br>    fun clearCache() {<br>        productCache.clear()<br>        categoryCache.clear()<br>    }<br>    fun invalidateCategory(category: String) {<br>        categoryCache.remove(category)<br>    }<br>}</pre><h3>10.2 Advanced RecyclerView Adapter with Indexing</h3><pre>class OptimizedUserAdapter : ListAdapter&lt;User, UserViewHolder&gt;(UserDiffCallback()) {<br>      // Multiple indices for different lookup needs<br>    private val positionById = HashMap&lt;String, Int&gt;()<br>    private val usersByDepartment = HashMap&lt;String, MutableSet&lt;User&gt;&gt;()<br>    private val selectedIds = HashSet&lt;String&gt;()<br>    private var onUserClick: ((User) -&gt; Unit)? = null<br>    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder {<br>        val view = LayoutInflater.from(parent.context)<br>            .inflate(R.layout.item_user, parent, false)<br>        return UserViewHolder(view)<br>    }<br>    override fun onBindViewHolder(holder: UserViewHolder, position: Int) {<br>        val user = getItem(position)<br>        val isSelected = user.id in selectedIds<br>        holder.bind(user, isSelected) {<br>            onUserClick?.invoke(user)<br>        }<br>    }<br>    override fun submitList(list: List&lt;User&gt;?) {<br>        super.submitList(list)<br>        rebuildIndices(list)<br>    }<br>    private fun rebuildIndices(users: List&lt;User&gt;?) {<br>        positionById.clear()<br>        usersByDepartment.clear()<br>        users?.forEachIndexed { index, user -&gt;<br>            positionById[user.id] = index<br>            usersByDepartment<br>                .getOrPut(user.department) { HashSet() }<br>                .add(user)<br>        }<br>    }<br>    fun updateUser(updatedUser: User) {<br>        val position = positionById[updatedUser.id] ?: return<br>        notifyItemChanged(position)<br>    }<br>    fun getUsersByDepartment(department: String): Set&lt;User&gt; {<br>        return usersByDepartment[department] ?: emptySet()<br>    }<br>    fun toggleSelection(userId: String) {<br>        if (selectedIds.contains(userId)) {<br>            selectedIds.remove(userId)<br>        } else {<br>            selectedIds.add(userId)<br>        }<br>        positionById[userId]?.let { position -&gt;<br>            notifyItemChanged(position)<br>        }<br>    }<br>    fun selectAll() {<br>        selectedIds.clear()<br>        currentList.forEach { selectedIds.add(it.id) }<br>        notifyDataSetChanged()<br>    }<br>    fun clearSelection() {<br>        selectedIds.clear()<br>        notifyDataSetChanged()<br>    }<br>    fun getSelectedUsers(): List&lt;User&gt; {<br>        return currentList.filter { it.id in selectedIds }<br>    }<br>    fun setOnUserClickListener(listener: (User) -&gt; Unit) {<br>        onUserClick = listener<br>    }<br>}<br>class UserDiffCallback : DiffUtil.ItemCallback&lt;User&gt;() {<br>    override fun areItemsTheSame(oldItem: User, newItem: User) =<br>        oldItem.id == newItem.id<br>    override fun areContentsTheSame(oldItem: User, newItem: User) =<br>        oldItem == newItem<br>}</pre><h3>10.3 Event Bus with Deduplication</h3><pre>class EventBus {<br>    private val subscribers = HashMap&lt;String, MutableSet&lt;(Event) -&gt; Unit&gt;&gt;()<br>    private val processedEventIds = HashSet&lt;String&gt;()<br>    private val eventHistory = LinkedHashMap&lt;String, Event&gt;(100, 0.75f, true)<br><br>    fun subscribe(eventType: String, handler: (Event) -&gt; Unit) {<br>        subscribers<br>            .getOrPut(eventType) { HashSet() }<br>            .add(handler)<br>    }<br>    fun unsubscribe(eventType: String, handler: (Event) -&gt; Unit) {<br>        subscribers[eventType]?.remove(handler)<br>    }<br>    fun publish(event: Event) {<br>        // Deduplication<br>        if (!processedEventIds.add(event.id)) {<br>            return // Already processed<br>        }<br>        // Store in history<br>        eventHistory[event.id] = event<br>        if (eventHistory.size &gt; 100) {<br>            val oldest = eventHistory.keys.first()<br>            eventHistory.remove(oldest)<br>            processedEventIds.remove(oldest)<br>        }<br>        // Notify subscribers<br>        subscribers[event.type]?.forEach { handler -&gt;<br>            handler(event)<br>        }<br>    }<br>    fun getEventHistory(): List&lt;Event&gt; {<br>        return eventHistory.values.toList()<br>    }<br>    fun clearHistory() {<br>        eventHistory.clear()<br>        processedEventIds.clear()<br>    }<br>}<br>data class Event(<br>    val id: String,<br>    val type: String,<br>    val payload: Any<br>)</pre><h3>10.4 Multi-Level Filter System</h3><pre>class ProductFilter {<br>    private val products = mutableListOf&lt;Product&gt;()<br><br>    // Multiple indices for efficient filtering<br>    private val productsByCategory = HashMap&lt;String, MutableSet&lt;Product&gt;&gt;()<br>    private val productsByBrand = HashMap&lt;String, MutableSet&lt;Product&gt;&gt;()<br>    private val productsByPriceRange = HashMap&lt;PriceRange, MutableSet&lt;Product&gt;&gt;()<br>    private val productsByTag = HashMap&lt;String, MutableSet&lt;Product&gt;&gt;()<br>    fun setProducts(newProducts: List&lt;Product&gt;) {<br>        products.clear()<br>        products.addAll(newProducts)<br>        rebuildIndices()<br>    }<br>    private fun rebuildIndices() {<br>        productsByCategory.clear()<br>        productsByBrand.clear()<br>        productsByPriceRange.clear()<br>        productsByTag.clear()<br>        products.forEach { product -&gt;<br>            // Index by category<br>            productsByCategory<br>                .getOrPut(product.category) { HashSet() }<br>                .add(product)<br>            // Index by brand<br>            productsByBrand<br>                .getOrPut(product.brand) { HashSet() }<br>                .add(product)<br>            // Index by price range<br>            val priceRange = getPriceRange(product.price)<br>            productsByPriceRange<br>                .getOrPut(priceRange) { HashSet() }<br>                .add(product)<br>            // Index by tags<br>            product.tags.forEach { tag -&gt;<br>                productsByTag<br>                    .getOrPut(tag) { HashSet() }<br>                    .add(product)<br>            }<br>        }<br>    }<br>    fun filter(criteria: FilterCriteria): List&lt;Product&gt; {<br>        val results = mutableSetOf&lt;Product&gt;()<br>        var isFirst = true<br>        // Apply category filter<br>        criteria.categories.takeIf { it.isNotEmpty() }?.let { categories -&gt;<br>            val categoryResults = categories<br>                .flatMap { productsByCategory[it] ?: emptySet() }<br>                .toSet()<br>            if (isFirst) {<br>                results.addAll(categoryResults)<br>                isFirst = false<br>            } else {<br>                results.retainAll(categoryResults)<br>            }<br>        }<br>        // Apply brand filter<br>        criteria.brands.takeIf { it.isNotEmpty() }?.let { brands -&gt;<br>            val brandResults = brands<br>                .flatMap { productsByBrand[it] ?: emptySet() }<br>                .toSet()<br>            if (isFirst) {<br>                results.addAll(brandResults)<br>                isFirst = false<br>            } else {<br>                results.retainAll(brandResults)<br>            }<br>        }<br>        // Apply price range filter<br>        criteria.priceRanges.takeIf { it.isNotEmpty() }?.let { ranges -&gt;<br>            val priceResults = ranges<br>                .flatMap { productsByPriceRange[it] ?: emptySet() }<br>                .toSet()<br>            if (isFirst) {<br>                results.addAll(priceResults)<br>                isFirst = false<br>            } else {<br>                results.retainAll(priceResults)<br>            }<br>        }<br>        // Apply tag filter<br>        criteria.tags.takeIf { it.isNotEmpty() }?.let { tags -&gt;<br>            val tagResults = tags<br>                .flatMap { productsByTag[it] ?: emptySet() }<br>                .toSet()<br>            if (isFirst) {<br>                results.addAll(tagResults)<br>                isFirst = false<br>            } else {<br>                results.retainAll(tagResults)<br>            }<br>        }<br>        // If no filters applied, return all products<br>        if (isFirst) {<br>            results.addAll(products)<br>        }<br>        return results.toList()<br>    }<br>    private fun getPriceRange(price: Double): PriceRange {<br>        return when {<br>            price &lt; 20 -&gt; PriceRange.UNDER_20<br>            price &lt; 50 -&gt; PriceRange.RANGE_20_50<br>            price &lt; 100 -&gt; PriceRange.RANGE_50_100<br>            else -&gt; PriceRange.OVER_100<br>        }<br>    }<br>}<br>data class FilterCriteria(<br>    val categories: Set&lt;String&gt; = emptySet(),<br>    val brands: Set&lt;String&gt; = emptySet(),<br>    val priceRanges: Set&lt;PriceRange&gt; = emptySet(),<br>    val tags: Set&lt;String&gt; = emptySet()<br>)<br>enum class PriceRange {<br>    UNDER_20, RANGE_20_50, RANGE_50_100, OVER_100<br>}<br>data class Product(<br>    val id: String,<br>    val name: String,<br>    val category: String,<br>    val brand: String,<br>    val price: Double,<br>    val tags: Set&lt;String&gt;<br>)</pre><h3>10.5 Jetpack Compose ViewModel with Optimized State</h3><pre>@HiltViewModel<br>class ShoppingCartViewModel @Inject constructor(<br>    private val productRepository: ProductRepository<br>) : ViewModel() {<br><br>    // Use Set for cart item IDs<br>    private val _cartItemIds = MutableStateFlow&lt;Set&lt;String&gt;&gt;(emptySet())<br>    val cartItemIds = _cartItemIds.asStateFlow()<br>    // Use HashMap for quick quantity lookup<br>    private val _itemQuantities = MutableStateFlow&lt;Map&lt;String, Int&gt;&gt;(emptyMap())<br>    val itemQuantities = _itemQuantities.asStateFlow()<br>    // Cache product details<br>    private val productCache = HashMap&lt;String, Product&gt;()<br>    fun addToCart(productId: String) {<br>        _cartItemIds.update { it + productId }<br>        _itemQuantities.update {<br>            it + (productId to (it[productId] ?: 0) + 1)<br>        }<br>    }<br>    fun removeFromCart(productId: String) {<br>        _cartItemIds.update { it - productId }<br>        _itemQuantities.update { map -&gt;<br>            map.toMutableMap().apply { remove(productId) }<br>        }<br>    }<br>    fun updateQuantity(productId: String, quantity: Int) {<br>        if (quantity &lt;= 0) {<br>            removeFromCart(productId)<br>        } else {<br>            _itemQuantities.update { it + (productId to quantity) }<br>        }<br>    }<br>    fun isInCart(productId: String): Boolean {<br>        return productId in _cartItemIds.value<br>    }<br>    fun getItemQuantity(productId: String): Int {<br>        return _itemQuantities.value[productId] ?: 0<br>    }<br>    suspend fun getCartProducts(): List&lt;Product&gt; {<br>        val missingIds = _cartItemIds.value - productCache.keys<br>        if (missingIds.isNotEmpty()) {<br>            missingIds.forEach { id -&gt;<br>                productRepository.getProduct(id)<br>                    .onSuccess { product -&gt;<br>                        productCache[id] = product<br>                    }<br>            }<br>        }<br>        return _cartItemIds.value.mapNotNull { productCache[it] }<br>    }<br>    fun clearCart() {<br>        _cartItemIds.value = emptySet()<br>        _itemQuantities.value = emptyMap()<br>    }<br>}<br>@Composable<br>fun ShoppingCartScreen(viewModel: ShoppingCartViewModel = hiltViewModel()) {<br>    val cartItemIds by viewModel.cartItemIds.collectAsState()<br>    val itemQuantities by viewModel.itemQuantities.collectAsState()<br>    LazyColumn {<br>        items(<br>            items = cartItemIds.toList(),<br>            key = { it }<br>        ) { productId -&gt;<br>            val quantity = itemQuantities[productId] ?: 0<br>            CartItem(<br>                productId = productId,<br>                quantity = quantity,<br>                onQuantityChange = { newQuantity -&gt;<br>                    viewModel.updateQuantity(productId, newQuantity)<br>                },<br>                onRemove = {<br>                    viewModel.removeFromCart(productId)<br>                }<br>            )<br>        }<br>    }<br>}</pre><h3>Conclusion</h3><p>HashMap and Set are powerful tools for optimizing Android applications when used correctly. The key principles to remember:</p><p><strong>Core Principles:</strong></p><ol><li>Use HashSet/HashMap for O(1) lookups instead of List’s O(n) scanning</li><li>Choose ArrayMap/ArraySet for small datasets (&lt; 1000 items) to save memory</li><li>Pre-size collections when the final size is known</li><li>Build lookup indices once, use them many times</li><li>Use Sets for uniqueness and membership testing</li><li>Use HashMaps for key-value caching and fast retrieval</li></ol><p><strong>Performance Impact:</strong></p><ul><li>Switching from List to HashSet for lookups can provide 100–1000x speedup</li><li>Proper indexing in RecyclerView adapters eliminates O(n) searches</li><li>Deduplication with Set is orders of magnitude faster than List</li><li>Pre-sized collections avoid costly resize operations</li></ul><p><strong>Android-Specific:</strong></p><ul><li>Prefer ArrayMap/ArraySet in framework components (Bundle, View tags)</li><li>Use HashMap/HashSet in application code for better performance</li><li>Leverage Sets in Compose for stable state and fast checks</li><li>Build multi-level indices for complex filtering scenarios</li></ul><p>Master these patterns and your Android apps will be significantly faster and more memory-efficient</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8657f067372b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Function References: Complete Professional Guide]]></title>
            <link>https://proandroiddev.com/kotlin-function-references-complete-professional-guide-63ef4d80f8de?source=rss-55f8aed942a------2</link>
            <guid isPermaLink="false">https://medium.com/p/63ef4d80f8de</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[function]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Tung Doan]]></dc:creator>
            <pubDate>Sat, 13 Dec 2025 03:43:43 GMT</pubDate>
            <atom:updated>2025-12-13T22:10:26.007Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w7bKVEXIsmB8ZYEMZFzdtQ.png" /></figure><h3>TL;DR — Quick Reference</h3><p><strong>When to use function references:</strong></p><ul><li>UI callbacks with ViewModels: viewModel::onButtonClick</li><li>Stable Compose references: onClick = viewModel::action</li><li>Constructor injection: ::MyClass</li><li>Top-level utility functions: list.forEach(::println)</li></ul><p><strong>When to use lambdas:</strong></p><ul><li>Need to capture variables: { item -&gt; handler.process(item) }</li><li>Inline operations: list.map { it * 2 }</li><li>Short, custom logic that differs from named functions</li></ul><p><strong>Performance hierarchy (fastest to slowest):</strong></p><ol><li>Unbound function reference (singleton, zero allocation)</li><li>Non-capturing lambda (single allocation)</li><li>Capturing lambda (allocation per invocation)</li><li>Bound function reference (allocation + capture overhead)</li></ol><h3>1. Introduction to Function References</h3><p>Function references in Kotlin allow you to reference existing functions without invoking them, treating functions as first-class citizens:</p><pre>fun greet(name: String) = println(&quot;Hello, $name&quot;)<br>val greeting: (String) -&gt; Unit = ::greet<br>greeting(&quot;Alice&quot;) // Output: Hello, Alice</pre><p>The :: operator creates a callable reference that wraps the function, enabling it to be passed as a parameter, stored in variables, or invoked later.</p><h3>Key Characteristics</h3><p>Function references differ fundamentally from lambdas in several ways:</p><ul><li>They reference existing named functions rather than defining inline logic</li><li>They generate reflection metadata (KFunction objects)</li><li>They follow different allocation patterns depending on whether they capture state</li><li>They cannot be inlined by the compiler in the same way lambdas can</li></ul><h3>2. Types and Syntax</h3><h3>2.1 Top-Level Function Reference</h3><p>References to functions defined at the package level:</p><pre>fun calculateTax(amount: Double): Double = amount * 0.15<br>val taxCalculator: (Double) -&gt; Double = ::calculateTax<br>val result = taxCalculator(100.0) // 15.0</pre><p><strong>Internal behavior:</strong> The compiler generates a singleton object implementing the appropriate functional interface. No allocation occurs when obtaining the reference.</p><h3>2.2 Member Function Reference (Unbound)</h3><p>References to instance methods without binding to a specific object:</p><pre>class UserRepository {<br>    fun fetchUser(id: String): User { ... }<br>}<br><br>val fetcher: (UserRepository, String) -&gt; User = UserRepository::fetchUser<br>val user = fetcher(repository, &quot;123&quot;)</pre><p>Note that the reference requires both the receiver object and the function parameters. The first parameter becomes the receiver.</p><h3>2.3 Bound Function Reference</h3><p>References to instance methods bound to a specific object:</p><pre>class EmailValidator {<br>    fun isValid(email: String): Boolean = email.contains(&quot;@&quot;)<br>}<br><br>val validator = EmailValidator()<br>val check: (String) -&gt; Boolean = validator::isValid<br>val result = check(&quot;test@example.com&quot;) // true\</pre><p><strong>Performance impact:</strong> Bound references capture the receiver instance, requiring allocation each time the reference is created. This makes them more expensive than unbound references.</p><h3>2.4 Extension Function Reference</h3><p>References to extension functions work similarly to regular functions:</p><pre>fun String.isValidEmail(): Boolean = this.contains(&quot;@&quot;) &amp;&amp; this.contains(&quot;.&quot;)<br><br>val validator: (String) -&gt; Boolean = String::isValidEmail<br>val result = validator(&quot;user@domain.com&quot;)</pre><p>Extension function references treat the extension receiver as the first parameter in the reference type.</p><h3>2.5 Constructor Reference</h3><p>References to constructors enable functional-style object creation:</p><pre>data class User(val id: String, val name: String)<br><br>val createUser: (String, String) -&gt; User = ::User<br>val user = createUser(&quot;001&quot;, &quot;Alice&quot;)<br>// Common in dependency injection<br>interface Factory&lt;T&gt; {<br>    fun create(id: String): T<br>}<br>class UserFactory : Factory&lt;User&gt; {<br>    override val create = ::User // Error: signature mismatch<br>}<br>// Proper usage with adapter<br>val userCreator: (String) -&gt; User = { id -&gt; User(id, &quot;Default&quot;) }</pre><h3>2.6 Property Reference</h3><p>References to properties provide access to getter/setter operations:</p><pre>class Configuration {<br>    var timeout: Int = 30<br>}<br><br>val config = Configuration()<br>val timeoutProperty = config::timeout<br>println(timeoutProperty.get()) // 30<br>timeoutProperty.set(60)<br>println(timeoutProperty.get()) // 60<br>// Top-level property<br>var appVersion = &quot;1.0&quot;<br>val versionRef = ::appVersion<br>println(versionRef.name) // &quot;appVersion&quot;</pre><p>Property references generate KProperty or KMutableProperty wrapper objects that support reflection operations.</p><h3>2.7 Companion Object Function Reference</h3><p>References to companion object functions:</p><pre>class DatabaseManager {<br>    companion object {<br>        fun connect(url: String): Connection { ... }<br>    }<br>}<br><br>val connector: (String) -&gt; Connection = DatabaseManager::connect<br>val connection = connector(&quot;jdbc:...&quot;)</pre><h3>3. Compiler Implementation Details</h3><h3>How Function References Are Generated</h3><p>When you write:</p><pre>fun processData(data: String): Result = ...<br><br>val processor = ::processData</pre><p>The Kotlin compiler generates synthetic code similar to:</p><pre>object ProcessDataReference : (String) -&gt; Result, KFunction1&lt;String, Result&gt; {<br>    override fun invoke(p1: String): Result = processData(p1)<br>    override val name = &quot;processData&quot;<br>    override fun call(vararg args: Any?): Any? = ...<br>    // Additional reflection metadata<br>}<br>val processor = ProcessDataReference</pre><h3>Bound Reference Generation</h3><p>For bound references:</p><pre>class DataProcessor {<br>    fun process(data: String): Result = ...<br>}<br><br>val processor = DataProcessor()<br>val reference = processor::process</pre><p>The compiler generates:</p><pre>class BoundProcessReference(private val receiver: DataProcessor) :<br>    (String) -&gt; Result, KFunction1&lt;String, Result&gt; {<br>    override fun invoke(p1: String): Result = receiver.process(p1)<br>    override val name = &quot;process&quot;<br>    // Reflection metadata<br>}<br>val reference = BoundProcessReference(processor</pre><p>Key difference: A new instance is created for each bound reference, capturing the receiver.</p><h3>Comparison with Lambda Generation</h3><p>Lambdas generate similar synthetic classes, but:</p><pre>val multiplier = 5<br>val lambda = { x: Int -&gt; x * multiplier }<br><br>// Generates something like:<br>class Lambda(private val multiplier: Int) : (Int) -&gt; Int {<br>    override fun invoke(x: Int) = x * multiplier<br>}<br>val lambda = Lambda(multiplier)</pre><p>Both capture state similarly, but lambdas don’t generate reflection metadata unless explicitly converted to function references.</p><h3>4. Performance Analysis</h3><h3>Allocation Patterns</h3><p>Understanding allocation behavior is critical for performance-sensitive code:</p><h3>Unbound Function Reference (Most Efficient)</h3><pre>fun square(x: Int) = x * x<br><br>val ref = ::square // Zero allocation - singleton<br>repeat(1000) {<br>    ref(it) // No allocation per call<br>}</pre><p><strong>Result:</strong> Single singleton object, zero per-call allocation.</p><h3>Non-Capturing Lambda</h3><pre>val lambda = { x: Int -&gt; x * x } // One allocation<br><br>repeat(1000) {<br>    lambda(it) // No additional allocation<br>}</pre><p><strong>Result:</strong> One allocation for the lambda instance.</p><h3>Capturing Lambda</h3><pre>val multiplier = 5<br>repeat(1000) {<br>    val lambda = { x: Int -&gt; x * multiplier } // Allocation each iteration<br>    lambda(it)<br>}</pre><p><strong>Result:</strong> New allocation each time the lambda is created if the capture context changes.</p><h3>Bound Function Reference (Least Efficient)</h3><pre>class Calculator {<br>    fun square(x: Int) = x * x<br>}<br><br>val calc = Calculator()<br>repeat(1000) {<br>    val ref = calc::square // Allocation each iteration<br>    ref(it)<br>}</pre><p><strong>Result:</strong> New BoundReference object allocated each time.</p><h3>Benchmark Results</h3><p>Approximate relative performance (normalized, smaller is better):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*uljmuPQSu4hsGs8ihV6UlA.png" /><figcaption>Benchmark Results for function reference types</figcaption></figure><p>Inline Functions Impact</p><p>Inline functions can eliminate lambda overhead entirely:</p><pre>inline fun processItems(items: List&lt;Int&gt;, operation: (Int) -&gt; Int): List&lt;Int&gt; {<br>    return items.map { operation(it) }<br>}<br><br>// Lambda is inlined - no allocation<br>val result = processItems(list) { it * 2 }<br>// Function reference cannot be inlined<br>val result = processItems(list, ::double) // Wrapper overhead remains</pre><p>Function references cannot be inlined because they must exist as callable objects to preserve reflection capabilities.</p><h3>5. Android and Jetpack Compose Usage</h3><h3>5.1 RecyclerView Adapters</h3><p><strong>Anti-pattern (allocates every bind):</strong></p><pre>class ItemAdapter : RecyclerView.Adapter&lt;ItemViewHolder&gt;() {<br>    override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {<br>        val item = items[position]<br>        holder.itemView.setOnClickListener {<br>            onItemClick(item) // Captures item<br>        }<br>    }<br>}</pre><p><strong>Better approach (stable reference):</strong></p><pre>class ItemViewHolder(view: View) : RecyclerView.ViewHolder(view) {<br>    lateinit var currentItem: Item<br>    fun bind(item: Item, onClick: (Item) -&gt; Unit) {<br>        currentItem = item<br>        itemView.setOnClickListener(this::handleClick)<br>    }<br>    private fun handleClick(view: View) {<br>        onItemClick(currentItem)<br>    }<br>}</pre><p><strong>Best approach (DiffUtil with stable IDs):</strong></p><pre>class ItemAdapter : ListAdapter&lt;Item, ItemViewHolder&gt;(ItemDiffCallback()) {<br>    override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {<br>        holder.bind(getItem(position), ::onItemClick)<br>    }<br><br>    private fun onItemClick(item: Item) {<br>        // Handle click<br>    }<br>}</pre><h3>5.2 ViewModel Integration</h3><p><strong>Efficient pattern:</strong></p><pre>class LoginViewModel : ViewModel() {<br>    private val _state = MutableStateFlow(LoginState())<br>    val state = _state.asStateFlow()<br><br>    fun onEmailChanged(email: String) {<br>        _state.update { it.copy(email = email) }<br>    }<br>    fun onPasswordChanged(password: String) {<br>        _state.update { it.copy(password = password) }<br>    }<br>    fun onLoginClick() {<br>        // Login logic<br>    }<br>}<br><br>@Composable<br>fun LoginScreen(viewModel: LoginViewModel) {<br>    val state by viewModel.state.collectAsState()<br>    TextField(<br>        value = state.email,<br>        onValueChange = viewModel::onEmailChanged // Stable reference<br>    )<br>    TextField(<br>        value = state.password,<br>        onValueChange = viewModel::onPasswordChanged<br>    )<br>    Button(onClick = viewModel::onLoginClick) {<br>        Text(&quot;Login&quot;)<br>    }<br>}</pre><p>Benefits:</p><ul><li>No lambda allocation on recomposition</li><li>Stable references prevent unnecessary recomposition</li><li>Clean separation of concerns</li></ul><h3>5.3 Jetpack Compose Modifiers</h3><p><strong>Anti-pattern:</strong></p><pre>@Composable<br>fun ItemList(items: List&lt;Item&gt;, onItemClick: (Item) -&gt; Unit) {<br>    LazyColumn {<br>        items(items) { item -&gt;<br>            Text(<br>                text = item.name,<br>                modifier = Modifier.clickable {<br>                    onItemClick(item) // New lambda each recomposition<br>                }<br>            )<br>        }<br>    }<br>}</pre><p><strong>Better pattern:</strong></p><pre>@Composable<br>fun ItemList(items: List&lt;Item&gt;, onItemClick: (Item) -&gt; Unit) {<br>    LazyColumn {<br>        items(<br>            items = items,<br>            key = { it.id } // Important for stability<br>        ) { item -&gt;<br>            ItemRow(<br>                item = item,<br>                onClick = onItemClick<br>            )<br>        }<br>    }<br>}<br><br>@Composable<br>fun ItemRow(item: Item, onClick: (Item) -&gt; Unit) {<br>    val clickHandler = remember(item.id) {<br>        { onClick(item) }<br>    }<br>    Text(<br>        text = item.name,<br>        modifier = Modifier.clickable(onClick = clickHandler)<br>    )<br>}@Composable<br>fun ItemRow(item: Item, onClick: (Item) -&gt; Unit) {<br>    val clickHandler = remember(item.id) {<br>        { onClick(item) }<br>    }<br>    Text(<br>        text = item.name,<br>        modifier = Modifier.clickable(onClick = clickHandler)<br>    )<br>}</pre><h3>5.4 Compose State Management</h3><p><strong>Using function references with state:</strong></p><pre>@Composable<br>fun CounterScreen(viewModel: CounterViewModel = viewModel()) {<br>    val count by viewModel.count.collectAsState()<br>    Column {<br>        Text(&quot;Count: $count&quot;)<br>        Row {<br>            Button(onClick = viewModel::increment) {<br>                Text(&quot;Increment&quot;)<br>            }<br>            Button(onClick = viewModel::decrement) {<br>                Text(&quot;Decrement&quot;)<br>            }<br>            Button(onClick = viewModel::reset) {<br>                Text(&quot;Reset&quot;)<br>            }<br>        }<br>    }<br>}<br><br>class CounterViewModel : ViewModel() {<br>    private val _count = MutableStateFlow(0)<br>    val count = _count.asStateFlow()<br>    fun increment() {<br>        _count.update { it + 1 }<br>    }<br>    fun decrement() {<br>        _count.update { it - 1 }<br>    }<br>    fun reset() {<br>        _count.value = 0<br>    }</pre><h3>5.5 Navigation with Function References</h3><pre>@Composable<br>fun AppNavigation(navController: NavHostController) {<br>    NavHost(navController, startDestination = &quot;home&quot;) {<br>        composable(&quot;home&quot;) {<br>            HomeScreen(<br>                onNavigateToProfile = navController::navigateToProfile,<br>                onNavigateToSettings = navController::navigateToSettings<br>            )<br>        }<br>        composable(&quot;profile&quot;) {<br>            ProfileScreen(onBack = navController::navigateUp)<br>        }<br>    }<br>}<br><br>fun NavController.navigateToProfile() {<br>    navigate(&quot;profile&quot;)<br>}<br>fun NavController.navigateToSettings() {<br>    navigate(&quot;settings&quot;)<br>}</pre><h3>6. Java Interop</h3><h3>Java Method References vs Kotlin Function References</h3><p><strong>Java method reference:</strong></p><pre>List&lt;String&gt; names = Arrays.asList(&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;);<br>names.forEach(System.out::println);<br><br>Function&lt;String, Integer&gt; lengthFn = String::length;</pre><p><strong>Kotlin equivalent:</strong></p><pre>val names = listOf(&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;)<br>names.forEach(::println)<br><br>val lengthFn: (String) -&gt; Int = String::length</pre><h3>Differences</h3><p><strong>Reflection metadata:</strong></p><ul><li>Java method references are lightweight</li><li>Kotlin function references carry KFunction metadata</li></ul><p><strong>Type compatibility:</strong></p><ul><li>Java method references convert to SAM interfaces</li><li>Kotlin function references are proper Kotlin function types</li></ul><p><strong>Performance:</strong></p><ul><li>Java method references are typically optimized by JVM</li><li>Kotlin function references have additional wrapper overhead</li></ul><h3>Calling Kotlin Function References from Java</h3><pre>// Kotlin<br>class UserService {<br>    fun validateUser(user: User): Boolean = user.isValid()<br>}<br><br>val validator = UserService::validateUser</pre><pre>// Java<br>Function2&lt;UserService, User, Boolean&gt; validator =<br>    UserServiceKt.getValidator();<br>UserService service = new UserService();<br>User user = new User();<br>boolean isValid = validator.invoke(service, user);</pre><h3>Calling Java Method References from Kotlin</h3><pre>// Java method<br>public class StringUtils {<br>    public static int getLength(String s) {<br>        return s.length();<br>    }<br>}<br><br>// Kotlin usage<br>val lengthFn: (String) -&gt; Int = StringUtils::getLength</pre><h3>7. Reflection Capabilities</h3><h3>Accessing Function Metadata</h3><pre>fun calculateTotal(price: Double, quantity: Int): Double = price * quantity<br><br>val calculator = ::calculateTotal<br>println(calculator.name) // &quot;calculateTotal&quot;<br>println(calculator.parameters.size) // 2<br>println(calculator.returnType) // kotlin.Double<br>println(calculator.parameters[0].name) // &quot;price&quot;<br>println(calculator.parameters[0].type) // kotlin.Double<br>println(calculator.parameters[1].name) // &quot;quantity&quot;<br>println(calculator.parameters[1].type) // kotlin.Int</pre><h3>Calling via Reflection</h3><pre>val result = calculator.call(19.99, 3) // Returns Any?<br>val typedResult = result as Double // 59.97</pre><h3>Property Reflection</h3><pre>class User(var name: String, val age: Int)<br><br>val user = User(&quot;Alice&quot;, 30)<br>val nameProperty = User::name<br>println(nameProperty.name) // &quot;name&quot;<br>println(nameProperty.get(user)) // &quot;Alice&quot;<br>nameProperty.set(user, &quot;Bob&quot;)<br>println(user.name) // &quot;Bob&quot;<br>// Read-only property<br>val ageProperty = User::age<br>println(ageProperty.get(user)) // 30<br>// ageProperty.set(user, 31) // Compile error - val property</pre><h3>Finding Functions at Runtime</h3><pre>class Calculator {<br>    fun add(a: Int, b: Int) = a + b<br>    fun subtract(a: Int, b: Int) = a - b<br>}<br><br>val calc = Calculator()<br>val functions = calc::class.memberFunctions<br>val addFunction = functions.find { it.name == &quot;add&quot; }<br>val result = addFunction?.call(calc, 5, 3) // 8</pre><h3>Performance Warning</h3><p>Reflection operations are significantly slower than direct calls:</p><pre>// Direct call: ~1ns<br>val result1 = calculator(19.99, 3)<br><br>// Reflection call: ~100ns<br>val result2 = calculator.call(19.99, 3)</pre><p>Avoid reflection in performance-critical code paths. Use direct function references when possible.</p><h3>8. Common Pitfalls</h3><h3>8.1 Allocating Bound References in Loops</h3><p><strong>Problem:</strong></p><pre>class DataProcessor {<br>    fun process(item: Item): Result = ...<br>}<br><br>val processor = DataProcessor()<br>val items = listOf(/* ... */)<br>// Allocates BoundReference object 1000 times<br>val results = items.map(processor::process)</pre><p><strong>Solution:</strong></p><pre>// Use unbound reference<br>val results = items.map(DataProcessor::process)<br>    .map { it.invoke(processor) }<br><br>// Or use lambda for clarity<br>val results = items.map { processor.process(it) }</pre><h3>8.2 Function References in Data Classes</h3><p><strong>Problem:</strong></p><pre>data class Action(<br>    val label: String,<br>    val handler: () -&gt; Unit<br>)<br><br>val action1 = Action(&quot;Save&quot;, viewModel::save)<br>val action2 = Action(&quot;Save&quot;, viewModel::save)<br>println(action1 == action2) // false - different reference instances</pre><p><strong>Solution:</strong> Use sealed classes or enums for action types:</p><pre>sealed class Action {<br>    abstract val label: String<br><br>    object Save : Action() {<br>        override val label = &quot;Save&quot;<br>    }<br>    object Cancel : Action() {<br>        override val label = &quot;Cancel&quot;<br>    }<br>}<br>// Handle actions separately<br>when (action) {<br>    Action.Save -&gt; viewModel.save()<br>    Action.Cancel -&gt; viewModel.cancel()<br>}</pre><h3>8.3 Overusing Function References for Small Operations</h3><p><strong>Problem:</strong></p><pre>// Function reference overhead exceeds operation cost<br>val numbers = (1..1000000).toList()<br>val doubled = numbers.map(::doubleValue)<br><br>fun doubleValue(x: Int) = x * 2</pre><p><strong>Solution:</strong></p><pre>// Lambda is faster for trivial operations<br>val doubled = numbers.map { it * 2 }</pre><h3>8.4 Function Reference Scope Issues</h3><p><strong>Problem:</strong></p><pre>class UserManager {<br>    private fun validateUser(user: User): Boolean = ...<br><br>    fun getValidator(): (User) -&gt; Boolean {<br>        return ::validateUser // Works<br>    }<br>}<br>fun getValidator(manager: UserManager): (User) -&gt; Boolean {<br>    return manager::validateUser // Error: Cannot reference private function<br>}</pre><p><strong>Solution:</strong> Expose public function or use lambda:</p><pre>class UserManager {<br>    fun validateUser(user: User): Boolean = ...<br>}<br><br>fun getValidator(manager: UserManager): (User) -&gt; Boolean {<br>    return manager::validateUser // Now works<br>}</pre><h3>8.5 Serialization Issues</h3><p><strong>Problem:</strong></p><pre>@Serializable<br>data class Command(<br>    val name: String,<br>    val action: () -&gt; Unit // Cannot be serialized<br>)</pre><p><strong>Solution:</strong> Separate data from behavior:</p><pre>@Serializable<br>data class CommandData(val name: String, val actionType: String)<br><br>class CommandRegistry {<br>    private val actions = mutableMapOf&lt;String, () -&gt; Unit&gt;()<br>    fun register(type: String, action: () -&gt; Unit) {<br>        actions[type] = action<br>    }<br>    fun execute(data: CommandData) {<br>        actions[data.actionType]?.invoke()<br>    }<br>}</pre><h3>8.6 Nullable Receiver References</h3><p><strong>Problem:</strong></p><pre>var processor: DataProcessor? = DataProcessor()<br><br>// This creates a new bound reference each time<br>val ref = processor?.let { it::process }</pre><p><strong>Solution:</strong></p><pre>// Store reference separately if needed multiple times<br>val processor: DataProcessor? = DataProcessor()<br>val processRef = processor?.let { it::process }<br><br>// Or handle null case explicitly<br>val results = if (processor != null) {<br>    items.map(processor::process)<br>} else {<br>    emptyList()<br>}</pre><h3>9. Best Practices</h3><h3>9.1 Choosing Between Lambdas and Function References</h3><p><strong>Use function references when:</strong></p><ul><li>Referencing existing named functions without additional logic</li><li>Need stable references for Compose or callbacks</li><li>Function is used in multiple places (DRY principle)</li><li>Zero-capture scenario (top-level or unbound member functions)</li></ul><p><strong>Use lambdas when:</strong></p><ul><li>Need to capture variables or state</li><li>Adding custom logic beyond simple delegation</li><li>Trivial operations where function reference overhead matters</li><li>Working with inline functions for performance</li></ul><h3>9.2 Naming Conventions</h3><pre>// Good: Clear function names that work well as references<br>class OrderService {<br>    fun processOrder(order: Order) { }<br>    fun cancelOrder(orderId: String) { }<br>    fun validateOrder(order: Order): Boolean { }<br>}<br><br>// Usage is clear<br>orders.forEach(orderService::processOrder)<br>orders.filter(orderService::validateOrder)<br>// Avoid: Generic names that lose meaning<br>class Service {<br>    fun handle(data: Any) { } // What does this handle?<br>    fun execute() { } // Execute what?<br>}</pre><h3>9.3 Compose Stability Patterns</h3><pre>@Composable<br>fun StableButtonExample(viewModel: MyViewModel) {<br>    // Stable - function reference doesn&#39;t change<br>    Button(onClick = viewModel::onButtonClick) {<br>        Text(&quot;Click Me&quot;)<br>    }<br>}<br><br>@Composable<br>fun UnstableButtonExample(onClick: () -&gt; Unit) {<br>    // Unstable if onClick is recreated every composition<br>    Button(onClick = onClick) {<br>        Text(&quot;Click Me&quot;)<br>    }<br>}<br>// Make it stable with remember<br>@Composable<br>fun StabilizedButtonExample(onEvent: (Event) -&gt; Unit) {<br>    val onClick = remember {<br>        { onEvent(Event.ButtonClicked) }<br>    }<br>    Button(onClick = onClick) {<br>        Text(&quot;Click Me&quot;)<br>    }<br>}</pre><h3>9.4 Extension Function Organization</h3><pre>// Group related extension function references<br>object NavigationActions {<br>    fun NavController.toHome() = navigate(&quot;home&quot;)<br>    fun NavController.toProfile() = navigate(&quot;profile&quot;)<br>    fun NavController.toSettings() = navigate(&quot;settings&quot;)<br>}<br><br>// Usage<br>with(NavigationActions) {<br>    Button(onClick = navController::toHome) { }<br>    Button(onClick = navController::toProfile) { }<br>}</pre><h3>9.5 Testing Function References</h3><pre>class UserViewModel {<br>    fun onNameChanged(name: String) { }<br>}<br><br>@Test<br>fun `function reference equality`() {<br>    val viewModel = UserViewModel()<br>    val ref1 = viewModel::onNameChanged<br>    val ref2 = viewModel::onNameChanged<br>    // Different instances - don&#39;t compare directly<br>    assertNotEquals(ref1, ref2)<br>    // Compare by invocation instead<br>    var capturedName = &quot;&quot;<br>    val testRef: (String) -&gt; Unit = { capturedName = it }<br>    testRef(&quot;Alice&quot;)<br>    assertEquals(&quot;Alice&quot;, capturedName)<br>}</pre><h3>9.6 Documentation</h3><pre>/**<br> * Processes user authentication with the given credentials.<br> *<br> * This function is designed to be used as a reference for callback registration.<br> * Example: `authManager.onLoginAttempt = viewModel::authenticateUser`<br> *<br> * @param credentials User credentials containing username and password<br> * @return Authentication result with token or error<br> */<br>fun authenticateUser(credentials: Credentials): AuthResult {<br>    // Implementation<br>}</pre><h3>10. Real-World Decision Matrix</h3><h3>Use Case Decision Guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*nW3JG1EzfBmlqJPSOy4_nQ.png" /><figcaption>Use Case Decision Guide</figcaption></figure><h3>Performance Decision Tree</h3><pre>Need to pass function as parameter?<br>├─ Is it a named function?<br>│  ├─ Yes → Is it bound to instance?<br>│  │  ├─ Yes (obj::method) → Use if called rarely<br>│  │  └─ No (::method) → Use function reference (best)<br>│  └─ No → Use lambda<br>└─ Does it capture variables?<br>   ├─ Yes → Lambda required<br>   └─ No → Consider extracting to named function</pre><h3>Example: Refactoring for Performance</h3><p><strong>Before:</strong></p><pre>@Composable<br>fun UserList(users: List&lt;User&gt;, onUserClick: (User) -&gt; Unit) {<br>    LazyColumn {<br>        items(users) { user -&gt;<br>            UserCard(<br>                user = user,<br>                onClick = { onUserClick(user) } // New lambda each recomposition<br>            )<br>        }<br>    }<br>}</pre><p><strong>After:</strong></p><pre>@Composable<br>fun UserList(users: List&lt;User&gt;, onUserClick: (User) -&gt; Unit) {<br>    LazyColumn {<br>        items(<br>            items = users,<br>            key = { it.id }<br>        ) { user -&gt;<br>            UserCard(<br>                user = user,<br>                onUserClick = onUserClick // Stable reference<br>            )<br>        }<br>    }<br>}<br><br>@Composable<br>fun UserCard(user: User, onUserClick: (User) -&gt; Unit) {<br>    val onClick = remember(user.id) {<br>        { onUserClick(user) }<br>    }<br>    Card(<br>        modifier = Modifier.clickable(onClick = onClick)<br>    ) {<br>        Text(user.name)<br>    }<br>}</pre><h3>Conclusion</h3><p>Kotlin function references provide powerful functional programming capabilities, but understanding their internal mechanics and performance characteristics is essential for writing efficient code, especially in Android and Jetpack Compose applications.</p><p>Key takeaways:</p><ol><li><strong>Unbound function references are highly efficient</strong> — they generate singleton objects with zero per-call allocation</li><li><strong>Bound references capture receivers</strong> — creating new instances and adding overhead</li><li><strong>Function references carry reflection metadata</strong> — making them heavier than Java method references</li><li><strong>Stability matters in Compose</strong> — function references prevent unnecessary recomposition</li><li><strong>Choose based on context</strong> — lambdas for capturing/trivial operations, references for stable callbacks</li></ol><p>Mastering these concepts enables you to write cleaner, more performant Kotlin code while leveraging the full power of functional programming paradigms.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63ef4d80f8de" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/kotlin-function-references-complete-professional-guide-63ef4d80f8de">Kotlin Function References: Complete Professional 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>
        <item>
            <title><![CDATA[How to Drink Coffee for Better Focus (Science-Based Tips)]]></title>
            <link>https://medium.com/@doanthanhtungnk123/how-to-drink-coffee-for-better-focus-science-based-tips-7cfa8017892c?source=rss-55f8aed942a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cfa8017892c</guid>
            <category><![CDATA[work]]></category>
            <category><![CDATA[coffee]]></category>
            <category><![CDATA[neuroscience]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[health]]></category>
            <dc:creator><![CDATA[Tung Doan]]></dc:creator>
            <pubDate>Sat, 06 Dec 2025 03:15:55 GMT</pubDate>
            <atom:updated>2025-12-06T03:15:55.084Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qm-RQiyVthYDDWXAdfU-UA.jpeg" /><figcaption><a href="https://unsplash.com/photos/three-person-holding-beverage-cups-6VhPY27jdps">https://unsplash.com/photos/three-person-holding-beverage-cups-6VhPY27jdps</a></figcaption></figure><p>Most people use coffee as a crutch. They drink it to survive the morning, but by 2:00 PM, they feel tired, anxious, or have a headache.</p><p>If you change <em>when</em> and <em>how</em> you drink coffee, it changes from a simple drink into a powerful tool for your brain. It can help you focus longer without the “jitters” or the afternoon crash.</p><p>Here are 5 simple habits to help you get more done.</p><h3>TL;DR (Too Long; Didn’t Read)</h3><p><strong>1. Wait 90 minutes:</strong> Let your body’s natural “wake-up hormone” (cortisol) wear off before adding caffeine.</p><p><strong>2. Add Sunlight:</strong> Combine coffee with morning light to wake up your brain and body at the same time.</p><p><strong>3. Drink Water First:</strong> Coffee makes you lose water. Hydrate before you caffeinate to prevent brain fog.</p><p><strong>4. Drink Small Amounts:</strong> Sip small amounts over time instead of chugging one huge cup to avoid anxiety.</p><p><strong>5. Create a Focus Habit:</strong> Teach your brain that the smell of coffee means “it is time for deep work.”</p><h3>1. The 90-Minute Rule</h3><p>Many people reach for a mug the second they roll out of bed. This is actually the worst time to drink it.</p><p>The Detailed Logic:</p><p>When you wake up, your body naturally releases a hormone called Cortisol. Think of Cortisol as nature’s caffeine. It naturally spikes in the morning to help you wake up.</p><ul><li>If you drink coffee while your Cortisol is high, you are adding energy on top of energy. This increases your stress levels and makes you build a tolerance to caffeine faster.</li><li>By waiting, you let your natural Cortisol do its job first. Then, when your energy starts to dip slightly (about 90 minutes later), the caffeine hits at the perfect moment to keep you going.</li></ul><p><strong>Your Action Plan:</strong></p><ul><li>Wake up and do your morning routine (shower, dress, eat) <em>without</em> coffee.</li><li>Wait <strong>60 to 90 minutes</strong> after waking up before your first sip.</li><li><em>Example:</em> If you wake up at 7:00 AM, your first coffee should be at 8:30 AM.</li></ul><h3>2. Combine Coffee with Sunlight</h3><p>Coffee affects your brain chemistry, but sunlight controls your biological clock (Circadian Rhythm).</p><p>The Detailed Logic:</p><p>Your eyes need to see natural light to tell your brain to stop producing “sleepy” hormones (like melatonin).</p><ul><li><strong>Coffee</strong> blocks the feeling of tiredness.</li><li><strong>Sunlight</strong> actively stimulates energy.</li><li>When you combine them, you get a “cleaner” energy. You feel awake because of the light, and focused because of the coffee. It reduces that nervous, jittery feeling you sometimes get from caffeine alone.</li></ul><p><strong>Your Action Plan:</strong></p><ul><li>Take your coffee cup outside, onto a balcony, or simply stand by a bright window.</li><li>Spend <strong>10 minutes</strong> looking at the daylight while you drink.</li><li><em>Note:</em> It works even on cloudy days!</li></ul><h3>3. The “Hydration Sandwich”</h3><p>Have you ever felt tired or had a headache after drinking coffee? That is usually dehydration, not the caffeine itself.</p><p>The Detailed Logic:</p><p>Caffeine is a diuretic, which means it makes your kidneys flush out water (it makes you pee more).</p><ul><li>Your brain is mostly water. Even mild dehydration causes “brain fog,” slower reaction times, and headaches.</li><li>If you drink coffee first thing in the morning (when you are already dehydrated from sleeping), you are starting your day with a “water deficit.”</li></ul><p><strong>Your Action Plan:</strong></p><p>Use the “Sandwich” method:</p><ol><li><strong>Bottom Bun:</strong> Drink one tall glass of water.</li><li><strong>The Meat:</strong> Drink your coffee.</li><li><strong>Top Bun:</strong> Drink another glass of water immediately after.</li></ol><p><strong>Rule:</strong> You are not allowed to touch the coffee until the first water glass is empty.</p><h3>4. Small Doses are Better (Micro-Dosing)</h3><p>The average coffee shop cup is huge (16oz or more). Drinking this much at once is a shock to your system.</p><p>The Detailed Logic:</p><p>When you drink a massive cup, your caffeine levels spike very high, very fast.</p><ul><li><strong>The Spike:</strong> This causes anxiety, shaking hands, and a racing heart.</li><li><strong>The Crash:</strong> Once your body processes that huge amount, your energy drops off a cliff, leaving you tired.</li><li><strong>The Solution:</strong> By drinking smaller amounts, you keep your caffeine levels in the “sweet spot” — alert, but calm.</li></ul><p><strong>Your Action Plan:</strong></p><ul><li>Avoid the “Venti” or “Grande” sizes.</li><li>Pour <strong>half a cup</strong> at 9:30 AM, and the <strong>other half</strong> at 11:30 AM.</li><li>This gives you steady energy for 4 hours, rather than a crazy burst for 1 hour.</li></ul><h3>5. The “Deep Work” Trigger</h3><p>Your brain is excellent at learning patterns. This is called <strong>associative learning</strong>. You can use this to your advantage.</p><p>The Detailed Logic:</p><p>If you drink coffee while scrolling through Instagram, watching TV, or chatting, your brain links coffee to “relaxation.”</p><p>However, if you only drink coffee when you are doing difficult work, your brain learns a new connection: Coffee = Focus.</p><p>Eventually, just the smell of coffee will trigger your brain to enter “work mode” before you even take a sip.</p><p><strong>Your Action Plan:</strong></p><ul><li><strong>Stop:</strong> Don’t drink coffee on the weekend while relaxing, or while checking emails in bed.</li><li><strong>Start:</strong> Make a ritual. Sit at your desk, open your most difficult project, and <em>then</em> pour your coffee.</li><li>Make coffee your “Work Partner,” not your “Relaxation Buddy.”</li></ul><h3>The Takeaway</h3><p>Coffee is a powerful biological tool. If you drink it randomly, it controls you. If you follow these simple rules — wait 90 minutes, add light, drink water, sip slowly, and use it as a trigger — you control it.</p><p>Turn your morning cup into a competitive advantage.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cfa8017892c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Ultimate Deep Dive into Android Spannable: Internals, Performance, Best Practices & Compose…]]></title>
            <link>https://medium.com/@doanthanhtungnk123/the-ultimate-deep-dive-into-android-spannable-internals-performance-best-practices-compose-35f40be68a5b?source=rss-55f8aed942a------2</link>
            <guid isPermaLink="false">https://medium.com/p/35f40be68a5b</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-textview]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[spannable]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Tung Doan]]></dc:creator>
            <pubDate>Sat, 22 Nov 2025 03:26:53 GMT</pubDate>
            <atom:updated>2025-11-22T03:26:53.405Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Ultimate Deep Dive into Android Spannable: Internals, Performance, Best Practices &amp; Compose Interop</h3><p>Text styling on Android looks simple on the surface: add some bold here, color some text there, make part of a sentence clickable.</p><p>But under the hood, Spannable is one of the most sophisticated subsystems in Android UI — powering everything from TextView to accessibility to Compose interoperability.</p><p>Most developers know <em>how</em> to use spans.</p><p>Very few know <strong>how they work</strong>, <strong>how expensive they are</strong>, or <strong>how they interact with modern UI toolkits like Jetpack Compose</strong>.</p><p>This guide goes deeper than anything you’ll find on the web — covering internals, performance modeling, best practices, and how Spannable integrates with AnnotatedString.</p><h3>1. Under the Hood: How Spannable Really Works</h3><p>Android text is built on three fundamental interfaces:</p><ul><li><strong>CharSequence</strong> — raw text, no styling.</li><li><strong>Spanned</strong> — text + immutable span metadata.</li><li><strong>Spannable</strong> — mutable version of Spanned.</li></ul><p>A SpannableString stores <em>text</em> separately from <em>spans</em>.</p><p>A span is an object attached to a character range:</p><pre>Text:  Hello world<br>Span:  [0..5) → Bold<br>Span:  [6..11) → URL(&quot;https://...&quot;)</pre><h3>1.1 Internal Data Structures</h3><p>SpannableString and SpannableStringBuilder internally maintain <strong>parallel arrays</strong>:</p><pre>spanObjects = [StyleSpan(BOLD), URLSpan(...)]<br>spanStarts  = [0,               6]<br>spanEnds    = [5,               11]<br>spanFlags   = [33,              33]</pre><p>Operations like getSpans() iterate linearly over spans (not characters), so cost is <strong>O(#spans)</strong>.</p><h3>1.2 Span Flags: Inclusive vs Exclusive</h3><p>Flags define how spans behave when inserting characters near the boundary:</p><ul><li>SPAN_EXCLUSIVE_EXCLUSIVE</li><li>SPAN-inclusive-variants…</li></ul><p><strong>Inclusive</strong> means the span “sticks” to its boundary.</p><p><strong>Exclusive</strong> means it does not expand when editing the boundary.</p><p>This affects editors, mentions, hashtags, and formatted input fields.</p><h3>1.3 Rendering Pipeline in TextView</h3><p>When assigned to a TextView:</p><ol><li>TextView stores the CharSequence.</li><li>Creates a Layout (StaticLayout / DynamicLayout).</li><li>Layout iterates characters and fetches spans affecting:</li></ol><ul><li>font style</li><li>color</li><li>size</li><li>underline/strike</li><li>links</li><li>custom draw logic (e.g., ImageSpan)</li></ul><p>4. MovementMethod handles user interaction for spans like ClickableSpan.</p><p>Rendering cost grows with:</p><ul><li>number of spans</li><li>complexity of spans</li><li>how often layout is invalidated</li></ul><p>Not with plain text length alone.</p><h3>2. Performance: What Actually Costs Time?</h3><h3>2.1 Span Operations</h3><p>These are <strong>span-count dependent</strong>, not text-length dependent:</p><ul><li>setSpan(span, start, end, flags)</li><li>removeSpan()</li><li>getSpans(start, end, type)</li></ul><p>More spans → slower operations.</p><h3>2.2 Layout Invalidation</h3><p>Every text change triggers:</p><ul><li>measuring</li><li>line breaking</li><li>span re-evaluation</li></ul><p>On high-frequency updates (chat apps, ticker UIs), this becomes significant.</p><h3>2.3 Object Allocations</h3><p>Creating many SpannableString objects → GC pressure.</p><p>Using a single SpannableStringBuilder is cheaper.</p><h3>2.4 When to Care</h3><p>Performance matters when:</p><ul><li>Rendering many items in RecyclerView</li><li>Animating spans every frame</li><li>Updating spans in response to typing</li><li>Building complex spans for large text blocks</li></ul><p>Otherwise, spans are cheap enough.</p><h3>3. Best Practices for Real-World Android Text</h3><h3>3.1 Prefer SpannableStringBuilder</h3><p>It is mutable and ideal for constructing complex text:</p><pre>val sb = SpannableStringBuilder()<br>sb.append(&quot;Hello &quot;)<br>val start = sb.length<br>sb.append(&quot;World&quot;)<br>sb.setSpan(StyleSpan(Typeface.BOLD), start, sb.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)</pre><h3>3.2 Keep Presentation Logic Separate</h3><p>Your app’s models should NOT depend on spans.</p><p>Represent the <em>intent</em> (“highlight username”), then map that to spans in the UI.</p><h3>3.3 Set MovementMethod for Clickable Spans</h3><pre>textView.text = spannable<br>textView.movementMethod = LinkMovementMethod.getInstance()<br>textView.highlightColor = Color.TRANSPARENT</pre><p>Without MovementMethod, clicks will never reach ClickableSpan.</p><h3>3.4 Cache Common Formatted Segments</h3><p>If you reuse identical styled text (chips, labels, tags), avoid recomputing spans.</p><h3>3.5 Avoid Layering Too Many Spans</h3><p>Don’t stack dozens of overlapping spans unless absolutely required — many spans degrade performance.</p><h3>4. Common Span Types and When to Use Them</h3><h3>Style and appearance</h3><ul><li>StyleSpan(Typeface.BOLD)</li><li>ForegroundColorSpan</li><li>BackgroundColorSpan</li><li>AbsoluteSizeSpan</li><li>RelativeSizeSpan</li></ul><h3>Semantic and structural</h3><ul><li>URLSpan (linking)</li><li>ClickableSpan (custom interaction)</li><li>ImageSpan (inline images)</li></ul><h3>Typography</h3><ul><li>SuperscriptSpan</li><li>SubscriptSpan</li><li>TypefaceSpan</li></ul><p>Always choose the <strong>most specific</strong> span that achieves the effect.</p><h3>5. Compose Interop: AnnotatedString ⇆ Spannable</h3><p>Jetpack Compose uses <strong>AnnotatedString</strong>, not Spannable.</p><p>It has:</p><ul><li>AnnotatedString.text</li><li>SpanStyle ranges</li><li>ParagraphStyle ranges</li><li>StringAnnotation for tags like URLs or custom metadata</li></ul><p>Almost 1:1 with Spannable but more Compose-oriented.</p><h3>5.1 Convert AnnotatedString → Spannable</h3><p>For interoperability with classic views:</p><pre>import androidx.compose.ui.text.android.toSpannable<br><br>val spannable = annotated.toSpannable()</pre><p>It maps:</p><ul><li>SpanStyle → StyleSpan / ForegroundColorSpan / SizeSpan etc.</li><li>StringAnnotation → URLSpan / metadata spans</li></ul><p>If font resolution is needed, you can pass Density and FontResolver.</p><h3>5.2 Convert Spanned → AnnotatedString</h3><pre>import androidx.compose.ui.text.android.toAnnotatedString<br><br>val annotated = spanned.toAnnotatedString()</pre><p>But custom spans require manual mapping:</p><pre>val sp = spannable.getSpans(0, spannable.length, Any::class.java)<br>val builder = AnnotatedString.Builder(spannable.toString())<br><br>for (span in sp) {<br>    val start = spannable.getSpanStart(span)<br>    val end = spannable.getSpanEnd(span)<br>    when (span) {<br>        is ForegroundColorSpan -&gt;<br>            builder.addStyle(SpanStyle(color = Color(span.foregroundColor)), start, end)<br>        is URLSpan -&gt;<br>            builder.addStringAnnotation(&quot;URL&quot;, span.url, start, end)<br>    }<br>}</pre><p>This is essential when migrating old XML-based UI to Compose.</p><h3>5.3 When to Convert vs Rebuild</h3><ul><li>If you have legacy span logic → convert.</li><li>If you’re building new UI → use AnnotatedString directly.</li><li>If you need backwards compatibility → maintain AnnotatedString as the source of truth and convert only for TextView.</li></ul><h3>6. Putting It All Together: Real-World Scenarios</h3><h3>6.1 Chat App Message Styling</h3><ul><li>Use SpannableStringBuilder for per-message formatting.</li><li>Cache common stylings like timestamps.</li><li>Avoid span creation inside ViewHolder binds if possible.</li></ul><h3>6.2 Clickable Terms &amp; Conditions</h3><ul><li>Use ClickableSpan with MovementMethod.</li><li>Use separate style spans for appearance.</li></ul><h3>6.3 Mixed Font Styling in Compose + AndroidView</h3><ul><li>Build AnnotatedString.</li><li>Convert to Spannable when rendering inside AndroidView.</li></ul><h3>6.4 Dynamic Highlighting During Search</h3><ul><li>Prefer rebuilding a single SpannableBuilder instead of multiple substring ops.</li></ul><h3>7. Summary (Copy-Paste Cheatsheet)</h3><p><strong>Spannable Internals</strong></p><ul><li>Uses arrays for spans; operations scale with span count.</li><li>Flags control how spans behave when editing.</li></ul><p><strong>Performance</strong></p><ul><li>Most expensive part is layout invalidation, not styling.</li><li>Reuse builders and cache styles for speed.</li></ul><p><strong>Best Practices</strong></p><ul><li>Use SpannableStringBuilder for dynamic text.</li><li>Keep logic separate from styling.</li><li>Always set MovementMethod for clickable spans.</li></ul><p><strong>Compose Interop</strong></p><ul><li>Use .toSpannable() and .toAnnotatedString() for bridging.</li><li>Map custom spans manually when needed.</li><li>Prefer AnnotatedString for new Compose code.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35f40be68a5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Coroutines: The Real Difference Between launch, async, and withContext (Deep Dive, Under…]]></title>
            <link>https://medium.com/@doanthanhtungnk123/kotlin-coroutines-the-real-difference-between-launch-async-and-withcontext-deep-dive-under-0e30d473ebfc?source=rss-55f8aed942a------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e30d473ebfc</guid>
            <category><![CDATA[async]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[launch]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[withcontext]]></category>
            <dc:creator><![CDATA[Tung Doan]]></dc:creator>
            <pubDate>Sat, 15 Nov 2025 03:14:34 GMT</pubDate>
            <atom:updated>2025-11-15T03:14:34.844Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kotlin Coroutines: The Real Difference Between launch, async, and withContext (Deep Dive, Under the Hood)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9WzsHCAqP-QTvyxN18xLTg.png" /></figure><p>Kotlin coroutines make concurrency look deceptively simple.</p><p>But beneath the friendly API sits a sophisticated runtime: continuations, compiler-generated state machines, structured concurrency, cooperative cancellation, dispatchers, and parent–child job hierarchies.</p><p>Most developers use:</p><ul><li>launch { }</li><li>async { }</li><li>withContext { }</li></ul><p>…but almost <strong>no one understands</strong>:</p><ul><li>what these functions <em>actually</em> generate,</li><li>how they alter the coroutine hierarchy,</li><li>how they impact error propagation,</li><li>when to use each one,</li><li>and the performance implications of choosing incorrectly.</li></ul><p>This is the definitive deep dive on launch, async, and withContext — including compiler transformations, lifecycle semantics, and real-world usage patterns.</p><h3>TL;DR (Copy-Paste Cheat Sheet)</h3><ul><li><strong>launch</strong> — fire-and-forget, no return value, errors propagate immediately, asynchronous.</li><li><strong>async</strong> — parallel decomposition, returns a Deferred, errors raise only on await().</li><li><strong>withContext</strong> — synchronous suspension + dispatcher switch, no new coroutine, returns result immediately.</li></ul><p><strong>Use</strong>:</p><ul><li><strong>launch</strong> → side effects, jobs, background sending, updating state</li><li><strong>async</strong> → parallel API calls, concurrent computations</li><li><strong>withContext</strong> → switching threads predictably, running blocking operations</li></ul><p><strong>Avoid</strong>:</p><ul><li>async inside launch without await</li><li>withContext inside tight UI recomposition</li><li>GlobalScope.launch</li><li>mixing async and launch incorrectly</li></ul><h3>1. Foundations: What a Coroutine Actually Is</h3><p>To understand launch, async, and withContext, you must understand what Kotlin is <em>doing behind the scenes</em>.</p><h3>1.1 A suspend function is not a thread — it is a compiler-generated state machine</h3><p>Given:</p><pre>suspend fun load() {<br>    val data = api.get()<br>    updateUi(data)<br>}</pre><p>The Kotlin compiler rewrites this into a class roughly like:</p><pre>class LoadContinuation(<br>    val completion: Continuation&lt;*&gt;<br>) : Continuation&lt;Any?&gt; {<br>    var state = 0<br>    override fun resumeWith(result: Result&lt;Any?&gt;) {<br>        when (state) {<br>            0 -&gt; {<br>                state = 1<br>                return api.getAsync(this)<br>            }<br>            1 -&gt; {<br>                state = 2<br>                return updateUiAsync(this)<br>            }<br>        }<br>    }<br>}</pre><p>Every suspend call is sliced into states.</p><p>launch, async, and withContext simply orchestrate these state machines.</p><h3>1.2 Job is the coroutine’s lifecycle</h3><ul><li>Every coroutine has a Job.</li><li>Jobs form a parent–child hierarchy.</li><li>Cancellation flows <strong>downward</strong>.</li><li>Exceptions flow <strong>upward</strong> (except inside supervisors).</li><li>Structured concurrency ensures no coroutine outlives its scope.</li></ul><p>This job hierarchy is where all differences between the three primitives originate.</p><h3>2. launch — Fire-and-Forget, Asynchronous Execution</h3><p>launch starts a <strong>new child coroutine</strong> and returns a Job.</p><pre>launch { ... }</pre><h3>2.1 What launch actually creates internally</h3><p>Under the hood:</p><pre>public fun CoroutineScope.launch(...) : Job {<br>    val coroutine = LaunchCoroutine(context, block)<br>    coroutine.start()<br>    return coroutine<br>}</pre><p>LaunchCoroutine is a state machine with:</p><ul><li>its own Job</li><li>its own parent</li><li>its own error boundary</li></ul><h3>2.2 Behavior characteristics of launch</h3><ul><li><strong>No return value</strong></li><li><strong>Asynchronous</strong> — code after launch runs immediately</li><li><strong>Exceptions propagate immediately</strong></li><li><strong>Cancels siblings and parent unless in a supervisor</strong></li><li><strong>Continues running until completed or cancelled</strong></li></ul><h3>2.3 When launch should be used</h3><ul><li>Updating app state</li><li>Calling repositories and posting results</li><li>Fire-and-forget analytics logging</li><li>Preloading data</li><li>Repeating background loops:</li></ul><pre>launch {<br>    while (isActive) {<br>        syncData()<br>        delay(3000)<br>    }<br>}</pre><h3>2.4 When launch is dangerous</h3><p>If you do:</p><pre>launch {<br>    val x = async { longTask() }<br>    // forgot to call x.await()<br>}</pre><p>You have:</p><ul><li>Hidden exceptions</li><li>Lost results</li><li>Orphaned coroutines</li></ul><p>launch is incorrect here — you needed coroutineScope.</p><h3>3. async — Deferred Results + Parallelism</h3><p>async is for <strong>concurrent computations that produce results.</strong></p><pre>val result = async { compute() }</pre><p>It returns a Deferred&lt;T&gt; — a Job that holds either:</p><ul><li>a successful value</li><li>a stored exception</li></ul><h3>3.1 async does not throw exceptions immediately</h3><p>This is the key difference.</p><pre>val d = async { error(&quot;Boom&quot;) }<br>println(&quot;Still running&quot;)<br>d.await() // error thrown HERE</pre><h3>3.2 Why async must always be awaited</h3><p>If you never call await():</p><ul><li>the exception isn’t thrown</li><li>the coroutine isn’t joined</li><li>cleanup isn’t performed</li></ul><p>This is why <strong>async inside launch is almost always wrong</strong>.</p><h3>3.3 Proper parallelism with async</h3><p>Parallel API calls:</p><pre>suspend fun load() = coroutineScope {<br>    val user = async { api.loadUser() }<br>    val feed = async { api.loadFeed() }<br>    Pair(user.await(), feed.await())<br>}</pre><p>Parallelism only happens inside coroutineScope.</p><p>Inside launch, async is not automatically waited.</p><h3>3.4 When async is wrong</h3><ul><li>fire-and-forget operations</li><li>updating UI</li><li>producing side effects</li><li>returning unit</li></ul><p>Async is only for <em>actual concurrency</em>.</p><h3>4. withContext — Synchronous Suspension + Dispatcher Switching</h3><p>withContext is the single most misunderstood coroutine primitive.</p><pre>withContext(Dispatchers.IO) {<br>    heavyFileRead()<br>}</pre><h3>4.1 withContext does NOT create a new coroutine</h3><p>This is the most important fact:</p><ul><li>No new Job</li><li>No new child coroutine</li><li>No new cancellation scope</li></ul><p>Instead:</p><ul><li>It <strong>suspends</strong> the current coroutine</li><li>Changes the dispatcher</li><li>Executes the block</li><li>Returns result and resumes the caller</li></ul><p>withContext is essentially a <strong>synchronous function call</strong> with a context override.</p><h3>4.2 When withContext is ideal</h3><ul><li>Running expensive I/O on IO dispatcher</li><li>Ensuring a block runs on Main or Default</li><li>Getting a final result synchronously in a suspend function</li><li>Preventing concurrency and side effects</li><li>Wrapping database operations</li></ul><p>Example:</p><pre>val user = withContext(IO) { dao.loadUser() }</pre><h3>4.3 When withContext is wrong</h3><ul><li>Doing parallelism (it runs sequentially)</li><li>Calling it many times in a Compose recomposition</li><li>Doing tiny operations with constant context switching</li><li>Doing heavy blocking inside a non-IO dispatcher</li></ul><h3>5. Deep Comparison (Behavior, Use Cases, Under-the-Hood Mechanics)</h3><p>Below is a refined expert comparison.</p><h3>5.1 launch vs async</h3><h3>Purpose</h3><ul><li>launch: side effects</li><li>async: return values</li></ul><h3>Error behavior</h3><ul><li>launch → throws immediately</li><li>async → throws on await</li></ul><h3>Lifecycle</h3><ul><li>launch → fire-and-forget</li><li>async → must await</li></ul><h3>Preferred use</h3><ul><li>launch: update UI, save DB, send events</li><li>async: parallel computation</li></ul><h3>5.2 launch vs withContext</h3><h3>Relationship</h3><ul><li>launch: asynchronous, creates Job</li><li>withContext: synchronous, no Job</li></ul><h3>Execution</h3><ul><li>launch: runs independently</li><li>withContext: blocks (suspends) until done</li></ul><h3>Use</h3><ul><li>launch: starting tasks</li><li>withContext: switching dispatchers</li></ul><h3>5.3 async vs withContext</h3><h3>async</h3><ul><li>concurrent</li><li>deferred result</li><li>await required</li></ul><h3>withContext</h3><ul><li>sequential</li><li>immediate result</li><li>ideal for I/O switching</li></ul><h3>6. Comparison Table (Professional, Clear, Complete)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*fZB68-wUMwHWMLm3uSu46A.png" /><figcaption>launch vs async vs withContext</figcaption></figure><h3>7. Real-World Scenarios (Advanced Understanding)</h3><h3>7.1 Correct parallel API loading</h3><pre>suspend fun loadBoth() = coroutineScope {<br>    val a = async(IO) { apiA() }<br>    val b = async(IO) { apiB() }<br>    combine(a.await(), b.await())<br>}</pre><p><strong>Why this works</strong>:</p><ul><li>coroutineScope waits for children</li><li>async runs concurrently</li><li>exceptions land on await()</li></ul><h3>7.2 Correct dispatcher switching</h3><pre>suspend fun render() {<br>    val file = withContext(IO) { reader.read() }<br>    withContext(Main) { ui.show(file) }<br>}</pre><p><strong>Under the hood</strong>:</p><ul><li>Saves continuation</li><li>Moves to IO thread pool</li><li>Performs I/O</li><li>Returns data</li><li>Moves back to Main</li><li>Resumes state machine</li></ul><h3>7.3 Incorrect async usage (dangerous)</h3><pre>launch {<br>    async { compute() }   // bad, not awaited<br>}</pre><p><strong>Why it’s wrong</strong>:</p><ul><li>Orphaned coroutine</li><li>Exception hides</li><li>Memory leak potential</li></ul><h3>8. Cancellation Behavior (Deep Technical Detail)</h3><h3>launch</h3><p>Cancels parent and siblings unless in supervisor.</p><pre>val job = launch {<br>    delay(1000)<br>}<br>job.cancel() // cooperative cancellation</pre><h3>async</h3><p>Cancellation cancels only its suspended work and triggers exception on await.</p><p>If awaiting never happens:</p><ul><li>exception never observed</li><li>but CoroutineExceptionHandler may still log it</li></ul><h3>withContext</h3><p>Cancellation cancels <em>this</em> block but keeps parent alive.</p><p>It obeys cooperative cancellation:</p><ul><li>delay</li><li>yield</li><li>IO dispatcher</li><li>suspending functions</li></ul><p>If you block thread manually (e.g., Thread.sleep):</p><ul><li>cancellation only takes effect after block ends</li><li>but coroutine still marked cancelled</li></ul><h3>9. Performance: The Real Cost of Each Primitive</h3><h3>launch</h3><ul><li>~100ns overhead</li><li>minimal allocations (Job + continuation)</li><li>ideal for many small tasks</li></ul><h3>async</h3><ul><li>Slightly slower</li><li>Needs Deferred</li><li>Stores result or exception</li><li>Good for parallel work, bad for side effects</li></ul><h3>withContext</h3><ul><li>The lightest abstraction</li><li>No new coroutine</li><li>One continuation jump</li><li>Heavy use can degrade performance (due to context switching)</li></ul><h3>10. Practical Rules (Final Quick Guide)</h3><h3>Use launch when:</h3><ul><li>You don’t need a result</li><li>You’re updating state</li><li>You’re sending events</li><li>You’re doing fire-and-forget work</li><li>You’re inside a ViewModel, Repository, UseCase</li></ul><h3>Use async when:</h3><ul><li>You’re doing <em>real</em> concurrency</li><li>You need to return values</li><li>You want structured parallelism</li><li>You will await the result</li></ul><h3>Use withContext when:</h3><ul><li>You’re switching dispatcher</li><li>You’re doing blocking I/O</li><li>You need a single result</li><li>You’re in a suspend function</li><li>You want synchronous behavior</li></ul><h3>Avoid:</h3><ul><li>async inside launch</li><li>GlobalScope usage</li><li>withContext inside hot UI loops</li><li>using launch where withContext is needed</li><li>using async where launch is needed</li><li>forgetting to await()</li></ul><h3>11. Summary: How to Never Misuse Coroutines Again</h3><p>You now understand:</p><ul><li>launch → asynchronous job</li><li>async → parallel computation with result</li><li>withContext → synchronous suspend call + dispatcher switch</li></ul><p>Under the hood:</p><ul><li>All coroutines compile into state machines</li><li>Jobs form hierarchies</li><li>Cancellation and exception propagation differ</li><li>Dispatcher switching is cheap but not free</li><li>Parallelism requires async + coroutineScope</li></ul><p>Mastering these three primitives gives you 90% of coroutine expertise.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e30d473ebfc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Your StateFlow Stops Emitting: The Hidden Lifecycle of SharingStarted in Kotlin]]></title>
            <link>https://medium.com/@doanthanhtungnk123/why-your-stateflow-stops-emitting-the-hidden-lifecycle-of-sharingstarted-in-kotlin-f84f120ae49c?source=rss-55f8aed942a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f84f120ae49c</guid>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[sharingstarted]]></category>
            <category><![CDATA[kotlin-stateflow]]></category>
            <category><![CDATA[statein]]></category>
            <category><![CDATA[whilesubscribed]]></category>
            <dc:creator><![CDATA[Tung Doan]]></dc:creator>
            <pubDate>Sat, 08 Nov 2025 03:56:18 GMT</pubDate>
            <atom:updated>2025-11-08T03:56:18.589Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w7bKVEXIsmB8ZYEMZFzdtQ.png" /></figure><p>If you’ve ever seen your StateFlow fail to collect after navigating back to a screen or wondered why WhileSubscribed() seems to “not work,” you’ve hit one of the most misunderstood parts of Kotlin’s Flow API: <strong>SharingStarted</strong>.</p><p>It’s the invisible lifecycle controller behind stateIn() and shareIn(), deciding <em>when</em> your upstream starts, <em>when</em> it stops, and <em>who</em> keeps it alive.</p><p>Let’s pull back the curtain.</p><h3>1. From Cold to Hot: The Reason stateIn Exists</h3><p>A regular Flow is <strong>cold</strong> — it restarts its upstream every time someone collects it.</p><pre>val users = flow {<br>    println(&quot;Fetching users...&quot;)<br>    emit(api.getUsers())<br>}</pre><p>Every collector runs api.getUsers() again.</p><p>To share the result and keep it “hot,” you use shareIn() or stateIn() — both powered by a <strong>shared coroutine scope</strong> and a <strong>SharingStarted strategy</strong>.</p><pre>val shared = flow<br>    .onEach { println(&quot;Upstream running&quot;) }<br>    .stateIn(<br>        scope = viewModelScope,<br>        started = SharingStarted.WhileSubscribed(5000),<br>        initialValue = emptyList()<br>    )</pre><p>But what does “WhileSubscribed(5000)” actually do?</p><h3>2. The SharingStarted Strategies</h3><p>The SharingStarted type tells your flow <em>when to start collecting from upstream</em> and <em>when to stop</em> based on downstream subscribers.</p><p>It has three built-in strategies (plus custom ones if you want):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*ufpEBXjLQOOVG_yuV5fGRg.png" /><figcaption>SharingStarted Strategies</figcaption></figure><p>Let’s break them down.</p><h3>Eagerly</h3><pre>SharingStarted.Eagerly</pre><ul><li>Starts upstream immediately when created.</li><li>Keeps collecting even if no one is subscribed.</li><li>Think of it as a permanently running “background stream.”</li></ul><p>Use when:</p><ul><li>You have global or always-on data (e.g., WebSocket, sensor listener).</li><li>You want to warm up caches at startup.</li></ul><h3>Lazily</h3><pre>SharingStarted.Lazily</pre><ul><li>Upstream starts when the <em>first collector</em> appears.</li><li>After that, it never stops — even if collectors go away.</li></ul><p>Use when:</p><ul><li>You want deferred initialization but permanent sharing (e.g., repository-level cache).</li></ul><h3>WhileSubscribed(stopTimeoutMillis, replayExpirationMillis)</h3><p>This one is the trickiest — and most misunderstood.</p><pre>SharingStarted.WhileSubscribed(<br>    stopTimeoutMillis = 5000,<br>    replayExpirationMillis = 0<br>)</pre><p>Here’s what actually happens:</p><ol><li>First subscriber → starts upstream.</li><li>All subscribers gone → starts a countdown (stopTimeoutMillis).</li><li>If a new subscriber appears before timeout, sharing continues.</li><li>If timeout expires → upstream stops and replay cache may clear (replayExpirationMillis).</li></ol><p>This small delay prevents <em>flapping</em> — restarting flows when you quickly rotate screen or navigate between fragments.</p><h3>Under the Hood: stateIn vs shareIn</h3><p>Both operators wrap your cold Flow in a SharedFlow internally.</p><ul><li>shareIn() returns a plain SharedFlow.</li><li>stateIn() builds on top of shareIn() but adds:</li><li>A <strong>replay cache of size 1</strong>.</li><li>An <strong>initial value</strong> for new collectors.</li><li>A coroutine that maintains a last-emitted snapshot.</li></ul><p>In essence:</p><pre>stateIn = shareIn(scope, started, replay = 1)</pre><blockquote><strong><em>replayExpirationMillis</em></strong><em> controls how long the last emission stays cached after the upstream stops.</em></blockquote><ul><li>0L → cache clears immediately when all collectors disappear.</li><li>Long.MAX_VALUE (the default) → keeps the replay forever.</li><li>Use a small value only if the cached data is large and short-lived.</li></ul><h3>3. Under the Hood: Subscription Count and State Machine</h3><p>Internally, WhileSubscribed is powered by a subscriptionCount StateFlow&lt;Int&gt; that tracks how many collectors are active.</p><pre>val subscriptionCount = MutableStateFlow(0)<br>val started = SharingStarted.WhileSubscribed()</pre><p>When subscriptionCount changes:</p><ul><li>From 0 → 1: Starts collecting the upstream.</li><li>From 1 → 0: Waits for timeout, then cancels upstream.</li><li>After timeout: Cancels job and optionally clears replay.</li></ul><p>Pseudocode (simplified):</p><pre>launch {<br>    subscriptionCount.collect { count -&gt;<br>        if (count &gt; 0) startUpstream()<br>        else delay(stopTimeoutMillis).also { stopUpstream() }<br>    }<br>}</pre><p>That’s why WhileSubscribed() behaves like lifecycle-aware LiveData — it reacts to the presence of observers.</p><blockquote><em>Think of WhileSubscribed as a lifecycle timeline:</em></blockquote><pre>collect() → active<br>no collectors → start timeout<br>timeout → stop upstream<br>new collector → restart</pre><blockquote><em>This simple state machine keeps your stream aligned with UI visibility.</em></blockquote><h3>4. Why “WhileSubscribed Doesn’t Collect” Isn’t a Bug</h3><p>Developers often run into this scenario:</p><pre>val uiState = flow<br>    .map { loadSomething() }<br>    .stateIn(viewModelScope, SharingStarted.WhileSubscribed(), initialState)</pre><p>Then inside Compose:</p><pre>val state by viewModel.uiState.collectAsState()</pre><p>…and nothing happens.</p><p>The reason? WhileSubscribed only starts when <strong>someone collects</strong>, but sometimes, due to lifecycle timing, the collector briefly unsubscribes before upstream starts.</p><p>Common triggers:</p><ul><li>Navigation transitions (fragment detached, reattached).</li><li>Lifecycle restarts (onStop → onStart).</li><li>collectAsState() unsubscribes when composition disposes.</li></ul><p>Since stopTimeoutMillis = 0 by default, the upstream stops instantly — before Compose re-subscribes.</p><p><strong>Fix</strong>: give it a buffer.</p><pre>stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), initialState)</pre><p>That 5-second grace window keeps your flow alive through short UI pauses.</p><h3>5. Lifecycle and Coroutine Scope Interactions</h3><p>Each stateIn or shareIn runs inside a coroutine scope.</p><p>When that scope is cancelled, the entire upstream dies.</p><pre>viewModelScope.launch {<br>    flow.stateIn(viewModelScope, SharingStarted.WhileSubscribed(), 0)<br>}</pre><ul><li>viewModelScope survives configuration changes, so perfect for UI data.</li><li>lifecycleScope dies on rotation, so sharing stops and restarts each time.</li></ul><p>If your stateIn is scoped to a destroyed lifecycle, it won’t emit again after recreation.</p><p>That’s why ViewModels should own shared flows; UI components should just collect them.</p><h3>6. Performance and Memory Considerations</h3><p>Every stateIn maintains a <strong>replay cache</strong> (size = 1 by default).</p><p>This means the last emitted value is always stored and delivered immediately to new subscribers.</p><p>Memory-wise:</p><ul><li>Eagerly and Lazily hold the upstream forever.</li><li>WhileSubscribed can release it after timeout (and optionally clear replay).</li></ul><p>Performance-wise:</p><ul><li>Use small stopTimeout for fast cleanup.</li><li>Use replayExpirationMillis = NEVER if you want to keep last value always available.</li><li>Avoid wrapping large data objects in stateIn unless immutable or cached.</li></ul><h3>7. Debugging &amp; Common Pitfalls</h3><h3>No Collector = No Upstream</h3><p>If no one collects your shared flow, upstream won’t run (except with Eagerly).</p><h3>Rapid Subscriptions</h3><p>Quickly attaching/detaching (e.g., fast navigation) may cause restart churn. Use a short stop timeout (<strong>5000</strong> milliseconds is good).</p><h3>Missing Replay</h3><p>shareIn without replay can cause missed emissions.</p><p>If you need “latest value,” prefer stateIn.</p><h3>Scope Cancellation</h3><p>When scope is cancelled (ViewModel cleared), the flow stops — even if you return to the screen later.</p><h3>Debug Trick</h3><p>Use the internal subscriptionCount to debug collector presence:</p><pre>viewModelScope.launch {<br>    myStateFlow.subscriptionCount.collect { count -&gt;<br>        Log.d(&quot;Debug&quot;, &quot;Collectors: $count&quot;)<br>    }<br>}</pre><h3>8. Practical Patterns</h3><h3>Always-On Cache</h3><pre>val cacheFlow = flow { emit(fetchData()) }<br>    .stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())</pre><p>Use for global caches, like user sessions or token monitors.</p><h3>UI-Bound Data</h3><pre>val uiFlow = flow { emit(loadUIState()) }<br>    .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), initial)</pre><p>Prevents unnecessary re-fetching when the screen briefly disappears.</p><h3>Lazy Initialization</h3><pre>val analyticsFlow = flow { emit(initializeAnalytics()) }<br>    .stateIn(viewModelScope, SharingStarted.Lazily, null)</pre><p>Great for one-time setup, only when first used.</p><h3>9. Best Practices</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*hRnXzXrmgF6OMc7fQa-l3Q.png" /><figcaption>Best Practices for SharingStarted strategies</figcaption></figure><p>Extra tips:</p><ul><li>Always collect in lifecycle-aware scopes (repeatOnLifecycle, collectAsStateWithLifecycle).</li><li>Keep stopTimeoutMillis between 3–5 seconds for smooth UI transitions.</li><li>Prefer stateIn over manual MutableStateFlow for cleaner caching.</li><li>Don’t use WhileSubscribed(0) unless you’re okay with instant stop behavior.</li></ul><h3>10. Summary: The Lifecycle of a Shared Flow</h3><p>When you call:</p><pre>flow.stateIn(scope, SharingStarted.WhileSubscribed(5000), initial)</pre><p>You’re effectively saying:</p><blockquote><em>“Start upstream only when someone’s watching, stop if everyone leaves for 5 seconds, but remember the last frame.”</em></blockquote><p>That’s not just a configuration — it’s your Flow’s <strong>lifecycle contract</strong>.</p><p>Understanding this lifecycle helps you design flows that are:</p><ul><li><strong>Predictable</strong> (no silent stops)</li><li><strong>Efficient</strong> (no redundant restarts)</li><li><strong>Lifecycle-aware</strong> (match Android UI behavior)</li></ul><p>If this deep dive helped you finally <em>understand</em> why your StateFlow stops emitting — drop a clap (or a few 👏👏👏) to help other developers discover it too.</p><p>Follow me here on Medium for more Kotlin deep dives — where we go beyond syntax and uncover what’s really happening <em>under the hood</em>: coroutines, Flow, concurrency, and modern Android architecture done right.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f84f120ae49c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hilt vs Koin: The Hidden Cost of Runtime Injection (and Why Compile-Time DI Wins)]]></title>
            <link>https://proandroiddev.com/hilt-vs-koin-the-hidden-cost-of-runtime-injection-and-why-compile-time-di-wins-3d8c522a073b?source=rss-55f8aed942a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d8c522a073b</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[koin]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[dagger-hilt]]></category>
            <dc:creator><![CDATA[Tung Doan]]></dc:creator>
            <pubDate>Sun, 02 Nov 2025 03:52:03 GMT</pubDate>
            <atom:updated>2025-11-07T06:56:18.331Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XUIP2YAXP5F6H1c5Pgx1yw.png" /></figure><p>Dependency Injection (DI) has quietly become the backbone of maintainable Android architecture.</p><p>It powers testability, modularity, and scalability — but <em>how</em> your DI framework works under the hood can mean the difference between a stable production app and subtle runtime landmines.</p><p>Most developers choose between two popular libraries: <strong>Hilt</strong> (built on top of Dagger) and <strong>Koin</strong>.</p><p>Both achieve the same goal — dependency graph management — but they do it in fundamentally different ways: <strong>compile-time vs runtime</strong>.</p><p>And that single design choice ripples through performance, safety, and architecture.</p><p>Let’s unpack the real difference.</p><h3>1. The Philosophy: Runtime vs Compile-Time</h3><p>Hilt and Koin are not just two DI frameworks — they represent two opposing philosophies.</p><p><strong>Hilt (Compile-Time DI):</strong></p><ul><li>Builds the dependency graph at <strong>compile time</strong>. The compiler generates all the necessary code — factories, providers, and dependency trees — before the app ever runs.</li></ul><p><strong>Koin (Runtime DI):</strong></p><ul><li>Builds the dependency graph at <strong>runtime</strong> using Kotlin’s DSL and reflection. Dependencies are registered and resolved dynamically as the app starts.</li></ul><p>This difference is fundamental.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*aPSs-hiGoAXQ0tolvaAy6w.png" /><figcaption>Hilt vs Koin</figcaption></figure><h3>2. How Hilt Actually Works</h3><p>When you annotate your module with @Module and @InstallIn, Hilt triggers the <strong>Dagger annotation processor</strong>.</p><p>During compilation, Dagger analyzes all @Inject, @Provides, and @Binds annotations to <strong>generate pure Java code</strong> that wires up your dependencies.</p><p>Example:</p><pre>@Module<br>@InstallIn(SingletonComponent::class)<br>object AppModule {<br>    @Provides fun provideApi(): ApiService = ApiService()<br>    @Provides fun provideRepository(api: ApiService) = Repository(api)<br>}</pre><p>The compiler then produces a factory class:</p><pre>public final class Repository_Factory implements Factory&lt;Repository&gt; {<br>    private final Provider&lt;ApiService&gt; apiProvider;<br>    @Override<br>    public Repository get() {<br>        return new Repository(apiProvider.get());<br>    }<br>}</pre><p>By the time your app runs, Hilt already knows every dependency path.</p><p>No reflection, no dynamic resolution, no surprises.</p><p>That’s why <strong>Hilt apps start faster and fail earlier</strong> — if a dependency graph is broken, you’ll know at compile time, not after release.</p><h3>3. How Koin Works Under the Hood</h3><p>Koin takes the opposite route — it builds the dependency graph <strong>on the fly</strong>.</p><p>When you write:</p><pre>val appModule = module {<br>    single { ApiService() }<br>    single { Repository(get()) }<br>}</pre><p>Koin stores each definition in a central registry.</p><p>At runtime, when you call get&lt;Repository&gt;(), Koin looks up the graph, resolves the dependencies recursively, and instantiates objects.</p><p>There’s <strong>no code generation</strong>, only <strong>runtime lookups and reflection</strong> to infer constructor parameters.</p><p>That makes Koin beautifully flexible — but also inherently slower and riskier for production apps.</p><p>If you misconfigure your graph or forget to load a module, the app won’t fail until you actually run that path.</p><h3>4. Performance and Startup Implications</h3><p>Startup time is where compile-time DI shines.</p><ul><li>Hilt generates the dependency graph <strong>once</strong>, at build time.</li><li>When your app launches, objects are created immediately with precompiled factories.</li></ul><p>Koin builds its graph <strong>at runtime</strong>, scanning definitions and resolving dependencies on demand.</p><p>The impact is measurable.</p><p>Benchmarks on real-world apps show:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*yuZmwPCrdPhZJ3HHk5jceA.png" /><figcaption>Hilt vs Koin in cold start time</figcaption></figure><p>While these numbers vary per device, the pattern holds:</p><p>Koin’s flexibility costs CPU and memory during initialization.</p><p>For small apps, that difference is negligible.</p><p>For large, modular, feature-heavy apps — it adds up fast.</p><h3>5. Developer Experience</h3><p>This is where opinions divide.</p><h3>Koin: The Kotlin-First Favorite</h3><p>Koin feels natural for Kotlin developers — no annotations, no processors, no Gradle plugins.</p><pre>val appModule = module {<br>    single { ApiService() }<br>    single { Repository(get()) }<br>}</pre><p>It’s ideal for prototypes, hackathons, and small apps where speed of iteration matters more than strict safety.</p><h3>Hilt: Verbose but Predictable</h3><p>Hilt adds boilerplate, but it also adds <strong>structure</strong>.</p><pre>@AndroidEntryPoint<br>class HomeViewModel @Inject constructor(<br>    private val repository: Repository<br>) : ViewModel()</pre><p>It’s not as “DSL-pretty,” but every dependency is explicit, lifecycle-aware, and verified at build time.</p><p>You trade initial setup for long-term stability.</p><h3>6. Scoping and Lifecycle Management</h3><p>Hilt’s biggest strength is its <strong>Android lifecycle integration</strong>.</p><p>It provides predefined components:</p><ul><li>SingletonComponent</li><li>ActivityRetainedComponent</li><li>ViewModelComponent</li><li>FragmentComponent</li><li>ServiceComponent</li></ul><p>Each scope maps directly to an Android lifecycle.</p><p>You never manually manage the DI graph — Hilt destroys and recreates dependencies with the lifecycle owner.</p><p>Koin, meanwhile, lets you define scopes manually:</p><pre>scope&lt;MainActivity&gt; {<br>    scoped { Presenter(get()) }<br>}</pre><p>This is more flexible but also more error-prone.</p><p>If you forget to close a scope or manage references incorrectly, you risk leaks or stale dependencies.</p><h3>7. Testability and Swapping Dependencies</h3><p>Testing is another area where compile-time DI has an edge.</p><ul><li><strong>Hilt</strong> provides @TestInstallIn to replace modules during tests, and an official testing API that handles setup and teardown automatically.</li><li><strong>Koin</strong> allows easy mocking by starting a new context in tests, but the replacement happens <strong>at runtime</strong>, so errors show later.</li></ul><p>If you write a lot of instrumentation tests, Hilt is cleaner and safer.</p><h3>8. Under the Hood Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*cul1UUk5FQRlMssw3ixqOQ.png" /><figcaption>Under the Hood Comparison between Hilt and Koin</figcaption></figure><h3>9. When to Use Which</h3><p><strong>Use Hilt when:</strong></p><ul><li>You’re building a <strong>large, multi-module</strong> Android app.</li><li>You want <strong>compile-time safety</strong> and <strong>predictable startup</strong>.</li><li>You need deep integration with Jetpack (ViewModel, WorkManager, etc.).</li><li>You’re scaling across a team or CI pipeline.</li></ul><p><strong>Use Koin when:</strong></p><ul><li>You’re prototyping or iterating quickly.</li><li>You want <strong>zero boilerplate</strong> and Kotlin DSL syntax.</li><li>You’re targeting <strong>Kotlin Multiplatform</strong>.</li></ul><h3>10. Best Practices</h3><ul><li>Prefer @Upsertstyle atomic graph registration — don’t mix manual injection and reflection.</li><li>Keep Hilt modules small and cohesive; avoid global singletons unless necessary.</li><li>Avoid field injection except for legacy code; constructor injection is safer and testable.</li><li>Benchmark Koin graph creation time before release.</li><li>If you migrate from Koin → Hilt, start from the <strong>core data and network layer</strong> first; features can follow incrementally.</li></ul><h3>11. Conclusion</h3><p>Koin gives you freedom; Hilt gives you guarantees.</p><p>Koin favors developer speed, Hilt favors system stability.</p><p>Compile-time DI means your app can’t even compile if the dependency graph is broken — and that’s exactly the kind of failure you want.</p><p>Runtime DI, in contrast, is flexible but unpredictable under scale.</p><p>So the question isn’t “which is simpler?”</p><p>It’s <strong>which one will still scale cleanly when your app has 100+ dependencies, 20 modules, and millions of users.</strong></p><p>And that’s where Hilt quietly wins.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d8c522a073b" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/hilt-vs-koin-the-hidden-cost-of-runtime-injection-and-why-compile-time-di-wins-3d8c522a073b">Hilt vs Koin: The Hidden Cost of Runtime Injection (and Why Compile-Time DI Wins)</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 Android Manifest Deep Dive: Everything Your App Tells the OS Before onCreate()]]></title>
            <link>https://medium.com/@doanthanhtungnk123/the-android-manifest-deep-dive-everything-your-app-tells-the-os-before-oncreate-314954f314ac?source=rss-55f8aed942a------2</link>
            <guid isPermaLink="false">https://medium.com/p/314954f314ac</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[manifest]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[android-permissions]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Tung Doan]]></dc:creator>
            <pubDate>Sat, 01 Nov 2025 03:41:44 GMT</pubDate>
            <atom:updated>2025-11-01T03:41:44.833Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XUIP2YAXP5F6H1c5Pgx1yw.png" /></figure><p>Every Android app begins long before MainActivity.onCreate() — it begins with the <strong>Manifest</strong>.</p><p>The AndroidManifest.xml file defines your app’s identity, components, permissions, and interactions with the operating system.</p><p>It’s not just metadata; it’s a <strong>declarative contract</strong> between your app and Android.</p><p>Yet, many developers treat it as boilerplate.</p><p>This guide dives beneath the surface — explaining how every Manifest tag shapes your app’s behavior, security, and visibility in the ecosystem.</p><h3>1. The Role of AndroidManifest.xml</h3><p>The Manifest tells Android:</p><ul><li>What components exist (activities, services, receivers, providers).</li><li>What permissions are needed or granted.</li><li>What features and devices are required.</li><li>How your app can be launched, exported, or restricted.</li><li>How it integrates with system and third-party frameworks.</li></ul><p>When you install an APK or AAB, Android parses the Manifest first — before any code runs.</p><p>The system uses this to register entry points, enforce permissions, and generate runtime configurations.</p><h3>2. Basic Structure</h3><p>A typical Manifest looks like this:</p><pre>&lt;manifest xmlns:android=&quot;&lt;http://schemas.android.com/apk/res/android&gt;&quot;<br>    package=&quot;com.example.app&quot;&gt;<br>    &lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;<br>    &lt;application<br>        android:name=&quot;.App&quot;<br>        android:label=&quot;@string/app_name&quot;<br>        android:icon=&quot;@mipmap/ic_launcher&quot;<br>        android:theme=&quot;@style/AppTheme&quot;<br>        android:exported=&quot;true&quot;&gt;<br>        &lt;activity<br>            android:name=&quot;.MainActivity&quot;<br>            android:exported=&quot;true&quot;&gt;<br>            &lt;intent-filter&gt;<br>                &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;<br>                &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;<br>            &lt;/intent-filter&gt;<br>        &lt;/activity&gt;<br>    &lt;/application&gt;<br>&lt;/manifest&gt;</pre><p>This single file defines everything the system needs to register your app.</p><h3>3. The exported Attribute</h3><p>Since Android 12 (API 31), all components that declare <strong>intent filters</strong> must explicitly specify android:exported.</p><pre>&lt;activity<br>    android:name=&quot;.MainActivity&quot;<br>    android:exported=&quot;true&quot;&gt;<br>    &lt;intent-filter&gt;<br>        &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;<br>        &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;<br>    &lt;/intent-filter&gt;<br>&lt;/activity&gt;</pre><ul><li>true → Component accessible from other apps (entry point).</li><li>false → Internal only (used via explicit intents within the app).</li></ul><p>This prevents unintended exposure of components that respond to implicit intents.</p><h3>4. Intent Filters</h3><p>&lt;intent-filter&gt; declares how a component responds to system or app-defined actions.</p><pre>&lt;intent-filter&gt;<br>    &lt;action android:name=&quot;android.intent.action.VIEW&quot; /&gt;<br>    &lt;category android:name=&quot;android.intent.category.DEFAULT&quot; /&gt;<br>    &lt;data android:scheme=&quot;https&quot; android:host=&quot;example.com&quot; /&gt;<br>&lt;/intent-filter&gt;</pre><p>This defines <strong>deep links</strong> and inter-app communication.</p><p>Each filter contains:</p><ul><li><strong>Action</strong> (what to do)</li><li><strong>Category</strong> (context, e.g., LAUNCHER)</li><li><strong>Data</strong> (URI or MIME type)</li></ul><p>Android matches these filters at runtime using intent resolution.</p><h3>5. Activities</h3><p>Activities represent user-facing screens.</p><pre>&lt;activity<br>    android:name=&quot;.MainActivity&quot;<br>    android:label=&quot;@string/app_name&quot;<br>    android:launchMode=&quot;singleTop&quot;<br>    android:theme=&quot;@style/Theme.App&quot;<br>    android:exported=&quot;true&quot; /&gt;</pre><p>Key attributes:</p><ul><li>launchMode: controls task behavior (standard, singleTop, singleTask, singleInstance)</li><li>taskAffinity: defines grouping across tasks</li><li>configChanges: prevents recreation on rotation or locale changes</li><li>windowSoftInputMode: keyboard and layout behavior</li><li>exported: required for entry points</li></ul><h3>6. Services</h3><p>A &lt;service&gt; runs operations in the background.</p><pre>&lt;service<br>    android:name=&quot;.SyncService&quot;<br>    android:exported=&quot;false&quot;<br>    android:foregroundServiceType=&quot;location&quot; /&gt;</pre><p>Types:</p><ul><li><strong>Foreground</strong> — persistent (music, navigation)</li><li><strong>Background</strong> — short tasks (restricted by Doze/App Standby)</li><li><strong>Bound</strong> — bound via IPC/Binder to other components</li></ul><p>Common permissions:</p><pre>&lt;uses-permission android:name=&quot;android.permission.FOREGROUND_SERVICE&quot; /&gt;</pre><h3>7. Broadcast Receivers</h3><p>Receivers react to system-wide broadcasts.</p><pre>&lt;receiver<br>    android:name=&quot;.BootReceiver&quot;<br>    android:enabled=&quot;true&quot;<br>    android:exported=&quot;true&quot;&gt;<br>    &lt;intent-filter&gt;<br>        &lt;action android:name=&quot;android.intent.action.BOOT_COMPLETED&quot; /&gt;<br>    &lt;/intent-filter&gt;<br>&lt;/receiver&gt;</pre><ul><li><strong>Static receivers</strong>: declared in Manifest; active even when app is closed.</li><li><strong>Dynamic receivers</strong>: registered at runtime via registerReceiver(); exist only while app is running.</li></ul><p><strong>Security tip:</strong></p><p>Restrict exported or use permissions to prevent external broadcasts from triggering internal logic.</p><h3>8. Content Providers</h3><p>Providers expose structured data to other apps using URI-based access.</p><pre>&lt;provider<br>    android:name=&quot;.data.AppProvider&quot;<br>    android:authorities=&quot;com.example.app.provider&quot;<br>    android:exported=&quot;false&quot;<br>    android:grantUriPermissions=&quot;true&quot; /&gt;</pre><ul><li><strong>authorities</strong>: unique identifier (must match URIs used in queries).</li><li><strong>grantUriPermissions</strong>: enables temporary URI access (e.g., via Intent.FLAG_GRANT_READ_URI_PERMISSION).</li></ul><p>Used by:</p><ul><li>Contacts</li><li>MediaStore</li><li>Room (via ContentProvider when using ContentProviderbacked access)</li></ul><h3>9. FileProvider: Secure File Sharing</h3><p>Direct file URIs (file://) were deprecated in Android 7.0+.</p><p>Use FileProvider to share files securely.</p><pre>&lt;provider<br>    android:name=&quot;androidx.core.content.FileProvider&quot;<br>    android:authorities=&quot;${applicationId}.provider&quot;<br>    android:exported=&quot;false&quot;<br>    android:grantUriPermissions=&quot;true&quot;&gt;<br>    &lt;meta-data<br>        android:name=&quot;android.support.FILE_PROVIDER_PATHS&quot;<br>        android:resource=&quot;@xml/file_paths&quot; /&gt;<br>&lt;/provider&gt;</pre><p>file_paths.xml example:</p><pre>&lt;paths&gt;<br>    &lt;external-path name=&quot;shared_images&quot; path=&quot;Pictures/&quot; /&gt;<br>&lt;/paths&gt;</pre><p>Generate content URI:</p><pre>val uri = FileProvider.getUriForFile(context, &quot;${BuildConfig.APPLICATION_ID}.provider&quot;, file)</pre><h3>10. Permissions and Protection Levels</h3><p>Permissions control access to protected APIs or components.</p><p>Levels:</p><ul><li><strong>Normal</strong> — automatically granted (e.g., VIBRATE)</li><li><strong>Dangerous</strong> — requires user approval (e.g., CAMERA)</li><li><strong>Signature</strong> — only for apps signed with same key</li></ul><p>Defining custom permission:</p><pre>&lt;permission<br>    android:name=&quot;com.example.permission.ACCESS_DATA&quot;<br>    android:protectionLevel=&quot;signature&quot; /&gt;</pre><p>Applying it:</p><pre>&lt;service<br>    android:name=&quot;.SecureService&quot;<br>    android:permission=&quot;com.example.permission.ACCESS_DATA&quot; /&gt;</pre><h3>11. Queries Element (Android 11+)</h3><p>Android 11 introduced <strong>package visibility restrictions</strong>.</p><p>To query other apps, declare &lt;queries&gt; in your Manifest.</p><pre>&lt;queries&gt;<br>    &lt;package android:name=&quot;com.google.android.youtube&quot; /&gt;<br>    &lt;intent&gt;<br>        &lt;action android:name=&quot;android.intent.action.VIEW&quot; /&gt;<br>        &lt;data android:scheme=&quot;https&quot; /&gt;<br>    &lt;/intent&gt;<br>&lt;/queries&gt;</pre><p>Without this, querying installed apps via PackageManager will return empty results.</p><h3>12. Metadata and SDK Integrations</h3><p>&lt;meta-data&gt; allows libraries and SDKs to read custom values via the PackageManager.</p><h3>Firebase</h3><pre>&lt;meta-data<br>    android:name=&quot;com.google.firebase.messaging.default_notification_icon&quot;<br>    android:resource=&quot;@drawable/ic_stat_notify&quot; /&gt;</pre><h3>AdMob</h3><pre>&lt;meta-data<br>    android:name=&quot;com.google.android.gms.ads.APPLICATION_ID&quot;<br>    android:value=&quot;@string/admob_app_id&quot; /&gt;</pre><h3>Google Maps</h3><pre>&lt;meta-data<br>    android:name=&quot;com.google.android.geo.API_KEY&quot;<br>    android:value=&quot;@string/google_maps_key&quot; /&gt;</pre><h3>Crashlytics</h3><pre>&lt;meta-data<br>    android:name=&quot;firebase_crashlytics_collection_enabled&quot;<br>    android:value=&quot;true&quot; /&gt;</pre><h3>13. Backup and Network Configuration</h3><h3>Backup Rules</h3><pre>&lt;application<br>    android:allowBackup=&quot;true&quot;<br>    android:fullBackupContent=&quot;@xml/backup_rules&quot; /&gt;</pre><h3>Network Security</h3><pre>&lt;application<br>    android:usesCleartextTraffic=&quot;false&quot;<br>    android:networkSecurityConfig=&quot;@xml/network_security_config&quot; /&gt;</pre><h3>Feature Declarations</h3><pre>&lt;uses-feature android:name=&quot;android.hardware.camera&quot; android:required=&quot;false&quot; /&gt;</pre><p>Used by Play Store to filter devices.</p><h3>14. Manifest Merging and Tools Attributes</h3><p>During Gradle builds, manifests from dependencies are merged into one.</p><p>Priority:</p><p>main &gt; buildType &gt; productFlavor &gt; library.</p><p>Override conflicts:</p><pre>&lt;activity<br>    android:name=&quot;.MainActivity&quot;<br>    tools:node=&quot;replace&quot;<br>    tools:ignore=&quot;ExportedReceiver&quot; /&gt;</pre><p>These tools: attributes are for build-time resolution, not runtime behavior.</p><h3>15. Common &lt;application&gt; Attributes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*p4GUte4s9wocN8PJE8ElPQ.png" /><figcaption>Common &lt;application&gt; Attributes</figcaption></figure><h3>16. Best Practices</h3><ol><li>Always declare android:exported explicitly for API 31+.</li><li>Use @xml/file_paths with FileProvider for sharing media.</li><li>Avoid exposing receivers or services unless necessary.</li><li>For deep links, prefer App Links with verified domains.</li><li>Declare &lt;queries&gt; if you use implicit intents or package lookups.</li><li>Use tools:node=&quot;merge&quot; carefully during manifest merges.</li><li>Keep android:allowBackup=&quot;false&quot; for sensitive apps.</li><li>Avoid largeHeap unless absolutely needed — it hides leaks.</li><li>Group permissions by protection level and document rationale.</li><li>Review generated manifest in /build/intermediates/merged_manifests/.</li></ol><h3>17. Master Tag Reference</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*7wJMsw3HsjZHo_pE4-EuYw.png" /><figcaption>Master Tag Reference in Manifest</figcaption></figure><h3>18. Closing Thoughts</h3><p>The Manifest defines not <em>what</em> your app does, but <em>how it exists</em> within Android.</p><p>It’s the blueprint Android reads before your first line of code ever runs.</p><p>Understanding it means understanding:</p><ul><li>App entry points</li><li>Permission models</li><li>IPC boundaries</li><li>SDK integrations</li></ul><p>Every &lt;activity&gt; and &lt;provider&gt; is more than a tag — it’s a declaration of trust and behavior.</p><p>Master the Manifest, and you master the foundation on which Android itself operates.</p><p>If this guide helped you see the Manifest in a new light, drop a clap (or a few 👏👏👏) — it helps other developers discover it.</p><p>Follow me here on Medium for more deep dives into Android internals, from compiler behavior to lifecycle architecture. Let’s keep pushing for clarity, precision, and better Android engineering.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=314954f314ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inline Value Classes in Kotlin: Zero-Cost Abstractions That Feel Like Magic]]></title>
            <link>https://medium.com/@doanthanhtungnk123/inline-value-classes-in-kotlin-zero-cost-abstractions-that-feel-like-magic-30dd3211b0fb?source=rss-55f8aed942a------2</link>
            <guid isPermaLink="false">https://medium.com/p/30dd3211b0fb</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[inline]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-value-class]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Tung Doan]]></dc:creator>
            <pubDate>Sun, 26 Oct 2025 03:36:12 GMT</pubDate>
            <atom:updated>2025-10-26T03:36:12.247Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XUIP2YAXP5F6H1c5Pgx1yw.png" /></figure><p>Kotlin’s <strong>inline value classes</strong> let you wrap primitive values in meaningful types <strong>without paying the runtime cost of objects</strong>.</p><p>They give you the <strong>type-safety of a class</strong> with the <strong>performance of a raw value</strong> — a concept that’s both elegant and surprisingly deep once you see what the compiler does under the hood.</p><h3>1. Why Inline Value Classes Exist</h3><p>In normal Kotlin, you often write wrapper types for better clarity or domain safety:</p><pre>data class UserId(val id: String)</pre><p>Nice and clean — but each UserId(&quot;123&quot;) is a real object, allocated on the heap.</p><p>If you pass millions of these around, you’re creating millions of objects.</p><p><strong>Inline value classes</strong> solve this: they let you create lightweight wrappers that <strong>compile down to the underlying value</strong> at runtime.</p><pre>@JvmInline<br>value class UserId(val id: String)</pre><p>This keeps your type safety (UserId ≠ String) but <strong>removes allocation</strong> — no extra object at runtime.</p><h3>2. How It Works Under the Hood</h3><p>When you write:</p><pre>@JvmInline<br>value class UserId(val id: String)</pre><p>The Kotlin compiler does two things:</p><ul><li><strong>At compile time:</strong> Enforces type safety — you can’t mix up UserId and String.</li><li><strong>At runtime (JVM):</strong> Rewrites calls so that UserId behaves like a plain String in most cases.</li></ul><p>So this:</p><pre>fun greet(id: UserId) = println(&quot;Hello, ${id.id}&quot;)</pre><p>Compiles roughly to:</p><pre>public static final void greet(String id) {<br>    System.out.println(&quot;Hello, &quot; + id);<br>}</pre><p>The wrapper disappears — the class is <strong>inlined</strong>.</p><p>That’s why they’re called <strong>inline value classes</strong>: the wrapper type exists only during compilation.</p><h3>3. Rules and Constraints</h3><p>To make this optimization possible, Kotlin imposes a few key restrictions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*RAzv-yCKZ_0RirfEPm2fmg.png" /><figcaption>Rules and Constraints for Inline value class</figcaption></figure><p>If you break these rules, Kotlin falls back to <strong>boxing</strong> (i.e., it allocates a real object).</p><h3>4. Boxing and Unboxing</h3><p>Inline classes are <strong>unboxed</strong> whenever possible, but <strong>boxed</strong> when required by language rules — for example:</p><pre>fun printAny(value: Any) {<br>    println(value)<br>}<br>printAny(UserId(&quot;123&quot;))</pre><p>Because Any expects an object, the compiler <strong>boxes</strong> the UserId into a real object at runtime.</p><p>Similarly, using generics or reflection may trigger boxing because the runtime needs a uniform object representation.</p><h3>5. Equality and Hashing</h3><ul><li>Structural equality (==) compares underlying values.</li><li>Referential equality (===) doesn’t make sense (no actual wrapper instance).</li></ul><p>Example:</p><pre>@JvmInline<br>value class UserId(val id: String)<br><br>val a = UserId(&quot;123&quot;)<br>val b = UserId(&quot;123&quot;)<br>println(a == b) // true<br>println(a === b) // compile error</pre><h3>6. Interop with Java</h3><p>From Java, value classes appear as <strong>boxed wrappers</strong>.</p><p>That’s why the @JvmInline annotation is required — it signals how the compiler should expose it to the JVM.</p><p>Example Java view:</p><pre>public final class UserId {<br>    private final String id;<br>    public UserId(String id) { this.id = id; }<br>    public String getId() { return id; }<br>}</pre><p>Java code still sees it as an object, so boxing applies automatically when crossing language boundaries.</p><h3>7. Use Cases</h3><h3>7.1 Domain-Driven Design Safety</h3><pre>@JvmInline<br>value class Email(val value: String)</pre><p>Now Email(&quot;abc&quot;) ≠ String, so you can’t accidentally pass an email to a method expecting a username.</p><h3>7.2 Type Safety in APIs</h3><pre>@JvmInline<br>value class Port(val number: Int)</pre><p>Prevents mixing ports and user IDs, even though both are Int.</p><h3>7.3 Performance-Critical Data Wrappers</h3><p>Used in serialization, networking, or parsers where you handle millions of small values.</p><h3>8. Inline Classes vs Type Aliases</h3><p>A <strong>typealias</strong> only changes the name, not the type:</p><pre>typealias UserId = String</pre><p>UserId and String are exactly the same at compile time — no safety at all.</p><p>Inline value classes, on the other hand, enforce type separation:</p><pre>val id: UserId = UserId(&quot;123&quot;)<br>// val s: String = id // ❌ compile error</pre><h3>9. Limitations and Gotchas</h3><ul><li>No mutable properties (var) allowed.</li><li>Generic constraints may force boxing.</li><li>null handling is special — UserId? can be boxed.</li><li>Avoid using as keys in hash maps when mixing boxed/unboxed values (can lead to equality mismatches).</li></ul><h3>10. Real Performance Benefit</h3><p>When unboxed, inline classes behave just like their primitive or reference base — no heap allocation, no extra indirection.</p><p>Benchmark comparisons (simplified):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*Wh-OQr3MkGc1s8-PvfAW2g.png" /><figcaption>Benchmark comparisons between data class and inline value class</figcaption></figure><p>They shine in hot loops, collections, and serialization pipelines.</p><h3>11. Future: Multi-Field Value Classes</h3><p>Kotlin 2.x introduces <strong>multi-field value classes</strong> (experimental), letting you define multiple properties with inline semantics.</p><p>They open the door to lightweight records similar to JVM Project Valhalla’s value types — combining <strong>immutability, zero-cost abstraction, and JVM efficiency.</strong></p><h3>12. Best Practices</h3><ul><li>Use inline classes for <strong>domain identifiers</strong> (UserId, Email, CurrencyCode).</li><li>Mark with @JvmInline for JVM interop clarity.</li><li>Avoid heavy logic inside; keep them pure wrappers.</li><li>Don’t rely on toString() for debugging (it may be inlined away).</li><li>Test null and boxing behaviors if passing across module boundaries.</li></ul><h3>13. Closing Thoughts</h3><p>Inline value classes embody Kotlin’s philosophy: <strong>make correctness free and performance implicit</strong>.</p><p>They turn what used to be a trade-off between readability and speed into a win-win abstraction.</p><p>When used wisely, they can make your domain models safer, your code cleaner, and your runtime lighter — all without you ever touching a heap allocation.</p><p>If you found this deep dive helpful, drop a clap (or a few 👏👏👏) to help others discover it — and follow for more under-the-hood Kotlin insights like this one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30dd3211b0fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>