<?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 Kirubakaran on Medium]]></title>
        <description><![CDATA[Stories by Kirubakaran on Medium]]></description>
        <link>https://medium.com/@kirupakaran094?source=rss-f2f70e824880------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZGqyx7oWruiq1wr_ozqtdQ.jpeg</url>
            <title>Stories by Kirubakaran on Medium</title>
            <link>https://medium.com/@kirupakaran094?source=rss-f2f70e824880------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 08:00:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kirupakaran094/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[Day 26: Anatomy of an Android Project — What All Those Files Actually Do]]></title>
            <link>https://kirupakaran094.medium.com/day-26-anatomy-of-an-android-project-what-all-those-files-actually-do-df4d79822fae?source=rss-f2f70e824880------2</link>
            <guid isPermaLink="false">https://medium.com/p/df4d79822fae</guid>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Kirubakaran]]></dc:creator>
            <pubDate>Sun, 07 Jun 2026 07:04:37 GMT</pubDate>
            <atom:updated>2026-06-07T07:11:25.206Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*28fDVLwxM6_3h7P4gtt_iw.png" /></figure><h4>Android with Kotlin for Absolute Beginners — Day 26 of the Series</h4><h3>Welcome to Phase 2.</h3><p>Yesterday you closed Phase 1 by finishing a 120-line Kotlin program from scratch. Today, you open Android Studio (or look at it conceptually if you haven’t installed it yet) and see something very different: a project tree with maybe 30 files, half of them looking like nonsense.</p><p>Your first reaction will probably be: <em>“what is all this and why are there so many config files?”</em></p><p>That reaction is universal. Every Android developer has had it. And the honest answer is: <strong>almost none of those files matter for what you’ll do today.</strong> Only four files do real work in a typical beginner project. The other twenty-something are scaffolding, configuration, and resources that Android Studio handles for you 99% of the time.</p><p>By the end of this article, you’ll know which four files matter, what every other file is roughly for, and how to navigate the project without getting lost. No coding today — this is orientation. Like Day 23 was for the capstone: think first, click around, then we build tomorrow.</p><h3>What You’ll Learn Today</h3><ul><li>✅ The three “layers” of any Android project: code, resources, configuration</li><li>✅ The four files that actually matter at this stage</li><li>✅ What every other folder is, in one line</li><li>✅ Your first encounter with @Composable and @Preview</li><li>✅ How to safely poke around without breaking anything</li></ul><h3>A Note on the Project You’re Looking At</h3><p>If you’ve installed Android Studio: when you create a <strong>New Project</strong> and pick <strong>“Empty Activity”</strong> under <strong>Phone and Tablet</strong>, you’ll get a Compose-based project. That’s Google’s modern default and what we’ll use throughout Phase 2.</p><p>If you haven’t installed Android Studio yet: that’s fine — read along. You’ll recognize everything when you eventually open a project for the first time. The structure has been stable for years.</p><p>A quick reminder of the wider plan: in Phase 1 we used the Kotlin Playground because it removed friction. From here on, we work in Android Studio because that’s where real Android apps are built. The transition is the biggest single jump in this whole series, but most of it is just <em>unfamiliarity</em>. Once you’ve seen the layout once, it stops being intimidating.</p><h3>The Three Layers</h3><p>Before anything else, here’s the mental model that makes the file tree click. Every Android project, no matter how big, breaks down into three layers:</p><p>Layer</p><p>What it is</p><p>Where it lives</p><p><strong>Code</strong></p><p>Your Kotlin — the actual logic</p><p>app/java/ (or kotlin/)</p><p><strong>Resources</strong></p><p>Everything visual: images, colors, strings, themes</p><p>app/res/</p><p><strong>Configuration</strong></p><p>How the project is built, what it requires, what it declares</p><p>Top-level Gradle files + AndroidManifest.xml</p><p>When you don’t know where a file belongs, ask yourself which layer it’s part of. That single question untangles ~90% of the confusion.</p><h3>The “Android” View vs the “Project” View</h3><p>Open the <strong>Project pane</strong> on the left side of Android Studio. At the top there’s a dropdown — by default it says <strong>“Android”</strong>. Click it and you’ll see other options including <strong>“Project”</strong>.</p><p>These two views show the same files in different layouts:</p><ul><li><strong>Android view</strong> — curated, grouped logically, what most tutorials show. Most folders you don’t need are hidden or collapsed. <strong>Use this 95% of the time.</strong></li><li><strong>Project view</strong> — the raw file structure on disk. Every config file visible, including the ones you never need to touch. Useful occasionally, but overwhelming as a default.</li></ul><p>If your screen looks completely different from what tutorials show, check the dropdown first. Switching to “Android” view fixes most “where is X?” confusion instantly.</p><h3>The Four Files That Actually Matter</h3><p>In the “Android” view, here are the four files you’ll spend nearly all your time in for the next few weeks:</p><h3>1. MainActivity.kt — Your App’s Entry Point</h3><p>Location: app/java/com.yourname.appname/MainActivity.kt</p><p>This is the file Android runs when your app starts. By default (with the modern Compose template), it looks roughly like this:</p><pre>class MainActivity : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent {<br>            YourAppNameTheme {<br>                Surface(<br>                    modifier = Modifier.fillMaxSize(),<br>                    color = MaterialTheme.colorScheme.background<br>                ) {<br>                    Greeting(&quot;Android&quot;)<br>                }<br>            }<br>        }<br>    }<br>}</pre><pre>@Composable<br>fun Greeting(name: String, modifier: Modifier = Modifier) {<br>    Text(text = &quot;Hello $name!&quot;, modifier = modifier)<br>}</pre><pre>@Preview(showBackground = true)<br>@Composable<br>fun GreetingPreview() {<br>    YourAppNameTheme {<br>        Greeting(&quot;Android&quot;)<br>    }<br>}</pre><p>There’s a lot of new stuff there. Don’t try to absorb it all today. The key shape:</p><ul><li>class MainActivity : ComponentActivity() — your class <strong>inherits</strong> from ComponentActivity (yes, Day 20’s inheritance!). Android calls onCreate when the app starts.</li><li>onCreate(...) — runs once when the activity is created. The first thing it does is call setContent { ... }.</li><li>setContent { ... } — this is the bridge. Everything <strong>inside</strong> the braces is your UI, written in Compose.</li><li>Greeting(...) and GreetingPreview() — small <strong>Composable functions</strong>. More on these in a moment.</li></ul><p>You don’t need to understand every line yet. You just need to know: <strong>MainActivity.kt is where your app starts, and </strong><strong>setContent { ... } is where your UI lives.</strong> That’s enough for today.</p><h3>2. AndroidManifest.xml — The App’s “Passport”</h3><p>Location: app/manifests/AndroidManifest.xml</p><p>Every Android app has a manifest. It’s an XML file (not Kotlin) that tells Android:</p><ul><li><strong>What’s in this app</strong> — which activities, which services</li><li><strong>What permissions it needs</strong> — camera, location, internet, etc.</li><li><strong>What hardware it requires</strong> — minimum Android version, screen sizes</li><li><strong>What it’s called</strong> — display name and icon</li></ul><p>You’ll touch this file occasionally — usually to register a new activity or add a permission. For now, just know it exists and what it’s for. Open it, glance at it, close it. Don’t edit it today.</p><h3>3. build.gradle.kts (Module: app) — The Dependency List</h3><p>Location: at the bottom of the project tree, you’ll see two Gradle files. The one labeled <strong>build.gradle.kts (Module: app)</strong> is the important one.</p><p>This file declares:</p><ul><li>What version of Android your app targets</li><li>What libraries your app depends on (Compose, networking, database, etc.)</li><li>Build settings like the package name and version number</li></ul><p>You’ll edit this file every time you want to add a new feature that needs a library. For example: “I want to use Room database” → add a line in here.</p><p>A simplified version of what you’ll see:</p><pre>android {<br>    namespace = &quot;com.yourname.appname&quot;<br>    compileSdk = 34<br>    defaultConfig {<br>        applicationId = &quot;com.yourname.appname&quot;<br>        minSdk = 24<br>        targetSdk = 34<br>    }<br>}</pre><pre>dependencies {<br>    implementation(&quot;androidx.compose.material3:material3:1.x.x&quot;)<br>    implementation(&quot;androidx.activity:activity-compose:1.x.x&quot;)<br>    // ... more dependencies<br>}</pre><p>Don’t memorize this. Just recognize it: <strong>this is where I add libraries when I need them.</strong></p><blockquote>The other Gradle file you’ll see — build.gradle.kts (Project: ...) — is the project-wide configuration. You’ll touch it less than once a month. Ignore it for now.</blockquote><h3>4. strings.xml — Your User-Facing Text</h3><p>Location: app/res/values/strings.xml</p><p>Any text the user sees should live here, not hard-coded in your Kotlin. Why? Because pulling text out into one place makes your app easier to translate, easier to update, and easier to maintain.</p><p>It looks like:</p><pre>&lt;resources&gt;<br>    &lt;string name=&quot;app_name&quot;&gt;My App&lt;/string&gt;<br>&lt;/resources&gt;</pre><p>To use a string in your code: getString(R.string.app_name). That R.string.app_name is Android’s way of referring to “the string with name app_name.”</p><p>Today, just know: <strong>all the words your users read should eventually live here.</strong></p><h3>Meet @Composable and @Preview</h3><p>You saw two unusual things in MainActivity.kt: @Composable and @Preview. Let me give you just enough to recognize them — full coverage comes when we dive into Compose properly.</p><h3>@Composable</h3><p>A line like:</p><pre>@Composable<br>fun Greeting(name: String) {<br>    Text(text = &quot;Hello $name!&quot;)<br>}</pre><p>That @Composable at the top is an <strong>annotation</strong>. It tells Android: <em>“this function describes a piece of UI.”</em> Compose then takes the function and uses it to draw something on the screen.</p><p>A few notable things:</p><ul><li>Composable functions look like normal Kotlin functions, but they’re called by the Compose framework, not by you directly</li><li>By convention, Composable function names start with a <strong>capital letter</strong> (Greeting, not greeting) — they describe UI elements, like classes do</li><li>Composable functions can only be called from <em>other</em> Composable functions</li></ul><p>Don’t worry about this until tomorrow. Just recognize: <strong>a function with </strong><strong>@Composable above it draws UI.</strong></p><h3>@Preview</h3><pre>@Preview(showBackground = true)<br>@Composable<br>fun GreetingPreview() {<br>    Greeting(&quot;Android&quot;)<br>}</pre><p>This @Preview annotation tells Android Studio: <em>“render this in the design pane next to my code.”</em> You get a live preview of your UI without running the app. It’s one of the best features in modern Android development — instead of building and waiting 30 seconds to see a change, the preview updates instantly.</p><p>The split-pane view (code on the left, preview on the right) is where you’ll do most of your Compose work. To enable it, look for the <strong>Code / Split / Design</strong> buttons in the top-right corner of any Compose file.</p><h3>Everything Else (One Line Each)</h3><p>Quick tour of folders and files you’ll see but rarely touch in Phase 2:</p><p>Folder or file</p><p>What it is</p><p>app/res/drawable/</p><p>Vector drawables and image resources (icons, illustrations)</p><p>app/res/mipmap/</p><p>App launcher icons (in various screen densities)</p><p>app/res/values/colors.xml</p><p>App color palette</p><p>app/res/values/themes.xml</p><p>Old-style XML themes (mostly unused in Compose projects)</p><p>app/java/.../ui/theme/</p><p>The Compose theme files (Color.kt, Theme.kt, Type.kt)</p><p>gradle/</p><p>The Gradle wrapper — automates the build tool itself. <strong>Never edit.</strong></p><p>gradle.properties</p><p>Project-wide build settings. Rarely edited.</p><p>local.properties</p><p>Your local machine’s SDK path. <strong>Never commit to version control.</strong></p><p>proguard-rules.pro</p><p>Code-shrinking rules for release builds. Phase 4 territory.</p><p>app/build/</p><p>Build output — generated files, don’t touch</p><p>.gitignore</p><p>Tells Git which files to skip. Standard.</p><p>If a folder isn’t in this table and you don’t see it in the <strong>Android view</strong>, it’s almost certainly safe to ignore.</p><h3>Safety Rules for Today</h3><p>A few simple don’ts that save beginners from real frustration:</p><h3>❌ Don’t manually create folders inside app/build/</h3><p>That folder is regenerated every time you build. Anything you put there will vanish.</p><h3>❌ Don’t rename or move files using your operating system’s file explorer</h3><p>Always rename via right-click → <strong>Refactor → Rename</strong> inside Android Studio. Manual file moves break the project references and produce confusing errors.</p><h3>❌ Don’t panic at Gradle sync errors</h3><p>“Gradle” is the build tool. When you change a configuration file, it re-syncs. Sometimes it fails. <strong>First fix to try:</strong> click <strong>File → Sync Project with Gradle Files</strong> (top menu). That fixes most issues. If not, restart Android Studio. If still not, that’s the kind of issue worth searching specific error text for online.</p><h3>❌ Don’t manually edit R.java or anything in the build/ folder</h3><p>These are generated automatically from your resources. Your changes will be overwritten on the next build.</p><h3>✅ Do explore the file tree freely</h3><p>Reading files doesn’t break anything. Open them, glance, close. This is how the structure starts feeling familiar.</p><h3>Mental Model Recap</h3><p>If you remember one diagram from today, make it this one:</p><pre>Your Android Project<br>│<br>├── 📝 Code  →  app/java/.../MainActivity.kt        ← where logic lives<br>│             app/java/.../ui/theme/                ← Compose theme files<br>│<br>├── 🎨 Resources  →  app/res/values/strings.xml      ← text<br>│                  app/res/values/colors.xml         ← colors<br>│                  app/res/drawable/                 ← images<br>│<br>└── ⚙️ Configuration  →  AndroidManifest.xml         ← app declaration<br>                       app/build.gradle.kts          ← dependencies &amp; build<br>                       gradle/, settings.gradle...   ← infrastructure</pre><p>Three layers. Four files you actually touch. Everything else is scaffolding.</p><h3>💪 Today’s Practice Challenge</h3><p>No coding today, but a few productive things to do:</p><ol><li><strong>If you have Android Studio installed:</strong> open the default project (or create a new Empty Activity project). Click through every file in the “Android” view. Don’t edit anything — just open, glance, close. The point is to feel the structure.</li><li><strong>Read the default </strong><strong>MainActivity.kt line by line.</strong> Identify:</li></ol><ul><li>The class MainActivity declaration (Day 18)</li><li>The inheritance from ComponentActivity (Day 20)</li><li>The override fun onCreate (Day 20)</li><li>The @Composable annotation</li><li>The string template inside Text(...) (Day 3)</li></ul><ol><li>Notice how much of it is <em>familiar</em>. Phase 1 is paying off — about half of MainActivity.kt is plain Kotlin you already know.</li><li><strong>Find the four key files yourself</strong>: MainActivity.kt, AndroidManifest.xml, build.gradle.kts (Module: app), and strings.xml. Locate them in the file tree without re-reading this article.</li><li><strong>(Optional, if Studio is installed)</strong> Click the green <strong>Run ▶️</strong> button at the top. If you have an emulator set up, your app will launch showing “Hello Android!” That’s the default Compose template running. Don’t worry if you can’t run it yet — that’s tomorrow’s article.</li></ol><h3>👉 Tomorrow: Day 27</h3><p>Tomorrow we <strong>run an actual app.</strong> We’ll cover how to set up an Android emulator (the virtual phone built into Android Studio), how to connect a real Android phone via USB, and what to do when the build button finally turns your code into something running on a screen. By the end of tomorrow, you’ll have seen your first Android app launch — written and run by you.</p><p><strong>See you tomorrow.</strong></p><h3>📚 Series Navigation</h3><p><strong>Previous:</strong> <a href="https://medium.com/@kirupakaran094/day-25-the-finale-completing-the-quiz-engine-closing-phase-1-1a7a705df530">Day 25 — Capstone Finale &amp; Phase 1 Wrap-Up</a> <strong>:</strong> Day 26 — Anatomy of an Android Project <strong>Next:</strong> Day 27 — Running Your First App <em>(link coming tomorrow)</em></p><p>If this article helped, a clap or share means the world. Phase 2 is the part of the journey where most “learn Android” series quietly disappear — your support keeps this one going.</p><h3>📊 References &amp; Further Reading</h3><ul><li><a href="https://developer.android.com/studio/projects/create-project">Official Android docs — Create a project</a></li><li><a href="https://developer.android.com/studio/projects">Official Android docs — Project overview</a></li><li><a href="https://developer.android.com/develop/ui/compose/tutorial">Jetpack Compose tutorial</a></li><li><a href="https://developer.android.com/studio/intro">Android Studio user guide</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df4d79822fae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 25: The Finale — Completing the Quiz Engine & Closing Phase 1]]></title>
            <link>https://kirupakaran094.medium.com/day-25-the-finale-completing-the-quiz-engine-closing-phase-1-1a7a705df530?source=rss-f2f70e824880------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a7a705df530</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Kirubakaran]]></dc:creator>
            <pubDate>Sat, 06 Jun 2026 01:36:00 GMT</pubDate>
            <atom:updated>2026-06-06T01:36:00.648Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bqsO8N0v3Wv_YDpEBTWgJQ.png" /></figure><h4>Android with Kotlin for Absolute Beginners — Day 25 of the Series</h4><h3>Twenty-Five Days Ago, You Couldn’t Write a Line of Code</h3><p>Today you finish a layered, type-safe Kotlin program — and close out Phase 1.</p><p>Yesterday you built the scoring engine: questions, answers, outcomes, and the logic that turns answers into scored results. Today we add the final layer — a <strong>report</strong> that summarizes performance, a <strong>formatted printer</strong> that makes it look professional, and the <strong>full assembly</strong> of everything into one complete program.</p><p>Then we’ll step back and look at how far you’ve come. Because it’s further than you probably realize.</p><p>Open the <a href="https://play.kotlinlang.org/">Kotlin Playground</a> with yesterday’s code. We’re building on top of it.</p><blockquote>I’ve taught and mentored a fair number of people learning to code. The ones who make it to a working capstone — a real program that does something, built from scratch — almost always keep going. Something shifts. You stop being “someone learning to code” and become “someone who codes.” If you’ve followed along and built these projects, that shift has already happened to you. Today just makes it official.</blockquote><h3>What You’ll Build Today</h3><ul><li>✅ The Grade enum and a function to compute it</li><li>✅ The ScoreReport data class with computed properties</li><li>✅ The report-building logic using collection operations</li><li>✅ A clean, formatted report printer</li><li>✅ The complete, assembled program</li><li>✅ A look back at Phase 1 — and forward to Phase 2</li></ul><h3>Step 1: The Grade Enum</h3><p>A letter grade is a fixed set of named values — an enum (Day 22), and we’ll give it a property so each grade knows its own minimum percentage:</p><pre>enum class Grade(val minPercent: Int) {<br>    A(90),<br>    B(70),<br>    C(50),<br>    F(0);</pre><pre>    companion object {<br>        fun fromPercent(percent: Int): Grade {<br>            return entries.firstOrNull { percent &gt;= it.minPercent } ?: F<br>        }<br>    }<br>}</pre><p>There’s one genuinely new piece here: the <strong>companion object</strong>.</p><p>A companion object holds functions and values that belong to the <em>type itself</em>, not to any individual instance. Grade.fromPercent(85) is called on Grade directly — you don’t need a specific grade instance to use it. Think of it as “functions that live on the class.” (You’ll see companion objects constantly in Android — they’re where things like factory functions and constants live.)</p><p>Inside fromPercent, we use entries (Day 22’s modern enum helper) and firstOrNull (a collection operation) to find the first grade whose minPercent the score meets. Because the entries are declared from highest to lowest, the first match is the right grade. The ?: F (Day 8 Elvis) is a safety net that can’t actually trigger here, but satisfies the compiler that we always return a Grade.</p><p>Test it quickly if you like: println(Grade.fromPercent(85)) should print B.</p><h3>Step 2: The ScoreReport Data Class</h3><p>This is the centerpiece of today. A ScoreReport holds the list of outcomes and <strong>computes everything else from them</strong> using computed properties (Day 19):</p><pre>data class ScoreReport(<br>    val outcomes: List&lt;Outcome&gt;,<br>    val passingPercent: Int = 50<br>) {<br>    val total: Int<br>        get() = outcomes.size</pre><pre>    val correct: Int<br>        get() = outcomes.count { it is Outcome.Correct }</pre><pre>    val incorrect: Int<br>        get() = outcomes.count { it is Outcome.Incorrect }</pre><pre>    val skipped: Int<br>        get() = outcomes.count { it is Outcome.Skipped }</pre><pre>    val percent: Int<br>        get() = if (total == 0) 0 else (correct * 100) / total</pre><pre>    val grade: Grade<br>        get() = Grade.fromPercent(percent)</pre><pre>    val passed: Boolean<br>        get() = percent &gt;= passingPercent<br>}</pre><p>Look at how much is happening here, and how cleanly:</p><ul><li><strong>outcomes</strong> is the only stored data. Everything else is <strong>computed</strong> (Day 19) — derived fresh each time from the outcomes list.</li><li><strong>count { it is Outcome.Correct }</strong> uses a collection operation (Day 15) with a type-check lambda (Day 22) to tally each category.</li><li><strong>percent</strong> guards against division by zero (if (total == 0) 0 else ...) — exactly the kind of edge-case thinking we’ve practiced. And it multiplies before dividing (Day 5).</li><li><strong>grade</strong> delegates to the Grade.fromPercent companion function we just wrote.</li><li><strong>passingPercent</strong> has a default value of 50 (Day 13) — callers can override it.</li></ul><p>This single data class answers every question you could ask about a quiz result, each property computing itself on demand. <em>This</em> is what well-designed Kotlin looks like.</p><h3>Step 3: Build the Report</h3><p>The report builder is almost trivial now, because ScoreReport does all the work itself. We just wrap the outcomes:</p><pre>fun buildReport(<br>    questions: List&lt;Question&gt;,<br>    answers: List&lt;Answer&gt;,<br>    passingPercent: Int = 50<br>): ScoreReport {<br>    val outcomes = scoreQuiz(questions, answers)<br>    return ScoreReport(outcomes, passingPercent)<br>}</pre><p>That’s it. It runs yesterday’s scoreQuiz and packages the result. The passingPercent parameter has a default (Day 13), so most callers can ignore it.</p><p>This is a sign of good design: when your data classes carry their own logic (via computed properties), the surrounding functions become tiny. The complexity lives in the right place.</p><h3>Step 4: The Report Printer</h3><p>Now the presentation layer — one function that turns a ScoreReport into beautiful output. This is where string templates (Day 3), when (Day 9), and collection operations (Day 15) all come together:</p><pre>fun printReport(report: ScoreReport) {<br>    println(&quot;==================================================&quot;)<br>    println(&quot;                 QUIZ RESULTS&quot;)<br>    println(&quot;==================================================&quot;)<br>    println(&quot;Questions:   ${report.total}&quot;)<br>    println(&quot;Correct:     ${report.correct}&quot;)<br>    println(&quot;Incorrect:   ${report.incorrect}&quot;)<br>    println(&quot;Skipped:     ${report.skipped}&quot;)<br>    println(&quot;--------------------------------------------------&quot;)<br>    println(&quot;Score:       ${report.percent}%&quot;)<br>    println(&quot;Grade:       ${report.grade}&quot;)<br>    println(&quot;Result:      ${if (report.passed) &quot;PASSED ✅&quot; else &quot;FAILED ❌&quot;}&quot;)<br>    println(&quot;--------------------------------------------------&quot;)</pre><pre>    val message = when (report.grade) {<br>        Grade.A -&gt; &quot;🏆 Outstanding! You&#39;ve mastered this material.&quot;<br>        Grade.B -&gt; &quot;🔥 Strong work. A little polish and you&#39;re at the top.&quot;<br>        Grade.C -&gt; &quot;📈 You passed — solid foundation, keep building.&quot;<br>        Grade.F -&gt; &quot;🌱 Not yet — review the material and try again. You&#39;ve got this.&quot;<br>    }<br>    println(message)<br>    println(&quot;==================================================&quot;)</pre><pre>    // Per-question review<br>    println()<br>    println(&quot;REVIEW:&quot;)<br>    report.outcomes.forEach { outcome -&gt;<br>        when (outcome) {<br>            is Outcome.Correct -&gt;<br>                println(&quot;  ✅ ${outcome.question.text}&quot;)<br>            is Outcome.Incorrect -&gt;<br>                println(&quot;  ❌ ${outcome.question.text}&quot;)<br>            is Outcome.Skipped -&gt;<br>                println(&quot;  ⏭️  ${outcome.question.text}&quot;)<br>        }<br>    }<br>}</pre><p>Two when blocks doing different jobs:</p><ul><li>The first picks an encouraging message based on the <strong>grade</strong> — exhaustive over all four Grade values (Day 22), no else needed.</li><li>The second produces a per-question review, exhaustive over the three Outcome types, smart-casting each (Day 8 + Day 22).</li></ul><p>Notice the printer touches <em>no</em> calculation logic — it just reads computed properties off the report and formats them. Presentation is cleanly separated from logic. That separation is exactly how real Android UIs relate to their data: the UI displays; the engine computes.</p><h3>Step 5: Assemble Everything</h3><p>Time to wire it all together. Here’s the complete main — it creates sample data, builds a report, and prints it:</p><pre>fun main() {<br>    val questions = listOf(<br>        Question(<br>            text = &quot;What keyword declares a read-only variable?&quot;,<br>            options = listOf(&quot;var&quot;, &quot;val&quot;, &quot;const&quot;, &quot;let&quot;),<br>            correctIndex = 1,<br>            difficulty = Difficulty.EASY<br>        ),<br>        Question(<br>            text = &quot;Which operator provides a default for null?&quot;,<br>            options = listOf(&quot;?.&quot;, &quot;?:&quot;, &quot;!!&quot;, &quot;==&quot;),<br>            correctIndex = 1,<br>            difficulty = Difficulty.MEDIUM<br>        ),<br>        Question(<br>            text = &quot;What does a sealed class restrict?&quot;,<br>            options = listOf(<br>                &quot;Number of instances&quot;,<br>                &quot;Where subtypes can be defined&quot;,<br>                &quot;Property visibility&quot;,<br>                &quot;Method count&quot;<br>            ),<br>            correctIndex = 1,<br>            difficulty = Difficulty.HARD<br>        ),<br>        Question(<br>            text = &quot;Which keyword creates an inheritable class?&quot;,<br>            options = listOf(&quot;public&quot;, &quot;open&quot;, &quot;abstract&quot;, &quot;final&quot;),<br>            correctIndex = 1,<br>            difficulty = Difficulty.MEDIUM<br>        ),<br>        Question(<br>            text = &quot;What does .map { } do to a list?&quot;,<br>            options = listOf(<br>                &quot;Filters items&quot;,<br>                &quot;Transforms each item&quot;,<br>                &quot;Sorts the list&quot;,<br>                &quot;Counts items&quot;<br>            ),<br>            correctIndex = 1,<br>            difficulty = Difficulty.EASY<br>        )<br>    )</pre><pre>    val answers = listOf(<br>        Answer.Picked(1),   // correct<br>        Answer.Picked(1),   // correct<br>        Answer.Picked(0),   // incorrect<br>        Answer.Skipped,     // skipped<br>        Answer.Picked(1)    // correct<br>    )</pre><pre>    val report = buildReport(questions, answers)<br>    printReport(report)<br>}</pre><p>Run the whole program. You should see:</p><pre>==================================================<br>                 QUIZ RESULTS<br>==================================================<br>Questions:   5<br>Correct:     3<br>Incorrect:   1<br>Skipped:     1<br>--------------------------------------------------<br>Score:       60%<br>Grade:       C<br>Result:      PASSED ✅<br>--------------------------------------------------<br>📈 You passed — solid foundation, keep building.<br>==================================================</pre><pre>REVIEW:<br>  ✅ What keyword declares a read-only variable?<br>  ✅ Which operator provides a default for null?<br>  ❌ What does a sealed class restrict?<br>  ⏭️  Which keyword creates an inheritable class?<br>  ✅ What does .map { } do to a list?</pre><p>🎉🎉🎉 <strong>You built it.</strong> A complete, layered, type-safe quiz engine — from scratch — in Kotlin.</p><h3>What You Actually Just Built</h3><p>Pause and take this in. This program contains:</p><ul><li><strong>2 enums</strong> (Difficulty, Grade) — one with a property and a companion object</li><li><strong>1 data class for data</strong> (Question) with a computed property</li><li><strong>2 sealed classes</strong> (Answer, Outcome) with multiple variants each</li><li><strong>1 data class for results</strong> (ScoreReport) with seven computed properties</li><li><strong>4 functions</strong> forming a clean pipeline</li><li><strong>Exhaustive </strong><strong>when</strong> blocks that the compiler verifies</li><li><strong>Collection operations</strong> doing all the counting and scoring</li><li><strong>Null-safe edge-case handling</strong> for mismatched inputs</li></ul><p>That’s not a toy. That’s the kind of code structure you’d find inside a real, shipping application. The only thing separating this from a real quiz app is a user interface — and that’s exactly what Phase 2 is about.</p><p>Here’s the thing worth sitting with: <strong>you didn’t learn any of this today.</strong> Every concept in this 120-line program came from the previous 24 days. Today you just <em>assembled</em> what you already knew. That’s what fluency feels like — reaching for the right tool without having to relearn it.</p><h3>Phase 1: A Look Back</h3><p>Twenty-five days ago, the series opened with a promise: take someone with zero coding experience and get them writing real Kotlin. Here’s the ground you’ve covered:</p><p><strong>Foundations (Days 1–11):</strong> environment setup, variables, data types, operators, conditionals, user-facing logic, null safety, when, loops — and two mini projects.</p><p><strong>Building blocks (Days 12–17):</strong> functions, default &amp; named arguments, collections, collection operations, lambdas — and a third project tying them together.</p><p><strong>Object-oriented Kotlin (Days 18–22):</strong> classes, computed properties, inheritance, interfaces, data classes, enums, sealed classes.</p><p><strong>The capstone (Days 23–25):</strong> designing and building a complete quiz engine that uses essentially everything.</p><p>If you built the projects — really built them, typing the code yourself — you are no longer a beginner. You’re a junior Kotlin programmer. That’s not flattery; it’s just what the skill list above adds up to.</p><blockquote>Take a screenshot of your finished capstone output and keep it somewhere. On the days Phase 2 feels hard — and some days will — look back at it. Twenty-five days ago this would have been incomprehensible to you. Now you built it. That’s your proof that the hard parts ahead are also learnable.</blockquote><h3>What’s Next: Phase 2</h3><p>Here’s where the series goes from here.</p><p><strong>Phase 2 — Your First Android Apps (Days 26+):</strong> We install Android Studio (yes, the big 10GB download we’ve avoided this whole time — you’ve earned it now). You’ll build your first actual Android app, learn how a project is structured, meet the Activity, build screens with real buttons and text. In Android, input comes from buttons and text fields, and it works beautifully.</p><p>Everything you built in Phase 1 carries forward. Your quiz engine? In Phase 2, you could wrap it in a real Android UI and have an actual study app on your phone. The data classes, the sealed states, the scoring logic — all of it transfers, unchanged.</p><p><strong>Phase 3 — Modern UI with Jetpack Compose.</strong> <strong>Phase 4 — Real-world apps, databases, networking, and publishing to the Play Store.</strong> It’s a long road, and it keeps getting more rewarding.</p><h3>💪 Today’s Challenge: Make the Capstone Yours</h3><p>This is the most important practice challenge of Phase 1. Don’t skip it.</p><ol><li><strong>Replace all the questions with your own.</strong> Write 5–10 questions about anything — Kotlin, your favorite topic, trivia. Run your engine on them.</li><li><strong>Add a new metric</strong> to ScoreReport — maybe accuracyAmongAnswered (correct out of <em>answered</em>, ignoring skips). A new computed property, a few minutes of work.</li><li><strong>Add a difficulty breakdown</strong> to the report — how many correct at each Difficulty level. Use groupBy { it.question.difficulty } (Day 14/15).</li><li><strong>Screenshot your output and share it.</strong> Tag it as your Phase 1 capstone. You earned the right to show it off.</li></ol><p><strong>Stretch goals (genuinely impressive if you finish them):</strong></p><ul><li>Add a points system where harder questions are worth more (give Difficulty a points property), and compute a weighted score.</li><li>Add a timeTakenSeconds field per answer and report the average time per question.</li><li>Refactor printReport to <em>return</em> a String instead of printing directly — that’s exactly the shape you’ll need to display it on an Android screen in Phase 2.</li></ul><h3>🎓 The Bigger Picture</h3><p>You’ve now done every introductory <a href="https://play.kotlinlang.org/koans/overview">Kotlin Koan</a> worth doing as a beginner. From here, the best practice isn’t more exercises — it’s <strong>building things</strong>. Extend this capstone. Build a small program of your own. The capstone proved you can; now go prove it to yourself again with something you invent.</p><h3>👉 Tomorrow: Day 26 — Phase 2 Begins</h3><p>Tomorrow, everything changes. We download Android Studio, create your first real Android project, and start building apps that run on an actual phone. Phase 1 was about learning the <em>language</em>. Phase 2 is about building the <em>thing</em>.</p><p>You’ve built the foundation. Now we build on it.</p><p><strong>See you in Phase 2.</strong></p><h3>📚 Series Navigation</h3><p><strong>Previous:</strong> Day 24 — Capstone Build, Part 1 <em>(link)</em> <strong>You are here:</strong> Day 25 — Capstone Finale &amp; Phase 1 Wrap-Up <strong>Next:</strong> Day 26 — Installing Android Studio (Phase 2 begins!) <em>(link coming tomorrow)</em></p><p>This is the end of Phase 1. If this series got you here, a clap or share genuinely helps other beginners find it — and it tells me to keep going. Thank you for showing up for 25 days. The hardest part — starting — is behind you.</p><h3>📊 References &amp; Further Reading</h3><ul><li><a href="https://kotlinlang.org/docs/object-declarations.html">Official Kotlin docs — Object declarations &amp; companion objects</a></li><li><a href="https://kotlinlang.org/docs/data-classes.html">Kotlin docs — Data classes</a></li><li><a href="https://developer.android.com/courses/android-basics-compose/course">Android Developers — Get started (preview of Phase 2)</a></li><li><a href="https://play.kotlinlang.org/koans/overview">Kotlin Koans (free beginner exercises)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a7a705df530" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 24: Building the Quiz Engine — Part 1: Data & Scoring]]></title>
            <link>https://kirupakaran094.medium.com/day-24-building-the-quiz-engine-part-1-data-scoring-70b68e7ca483?source=rss-f2f70e824880------2</link>
            <guid isPermaLink="false">https://medium.com/p/70b68e7ca483</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Kirubakaran]]></dc:creator>
            <pubDate>Fri, 05 Jun 2026 01:51:00 GMT</pubDate>
            <atom:updated>2026-06-05T01:51:00.653Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AqKiks9f7nN9kxOmbqJizg.png" /></figure><h4>Android with Kotlin for Absolute Beginners — Day 24 of the Series</h4><h3>Yesterday We Designed. Today We Build.</h3><p>Yesterday was the blueprint. Today we lay the foundation and frame the walls.</p><p>By the end of this article, you’ll have a working <strong>scoring engine</strong>: the part of the quiz system that takes a list of questions and a list of the user’s answers, and produces a list of outcomes — correct, incorrect, or skipped — for each one. That’s the hard half of the project.</p><p>Tomorrow (Day 25) we finish it: the report, the formatting, and the final assembly.</p><p>Open the <a href="https://play.kotlinlang.org/">Kotlin Playground</a> in a fresh tab. We’re going to build this up piece by piece, testing as we go — exactly the way real software gets written. Don’t paste the whole thing at the end; build it incrementally and run after each step so you catch mistakes early.</p><blockquote>The way we build today is the way I actually work: one small piece at a time, running the code after each addition. Beginners often try to write the whole program, then run it once and drown in errors. Build small, run often. It’s slower per step but far faster overall — and far less frustrating.</blockquote><h3>What You’ll Build Today</h3><ul><li>✅ The supporting enums (Difficulty)</li><li>✅ The data classes (Question)</li><li>✅ The sealed classes (Answer, Outcome)</li><li>✅ The core scoring function</li><li>✅ A test run that proves the scorer works</li></ul><h3>Step 1: The Difficulty Enum</h3><p>Let’s start with the simplest piece — a fixed set of difficulty levels. This is a textbook enum (Day 22):</p><pre>enum class Difficulty {<br>    EASY, MEDIUM, HARD<br>}</pre><p>That’s it. Three named values, nothing more for now. Type it into the Playground.</p><p>We can’t run anything meaningful yet — there’s no main — but this compiles. We’ll build on it.</p><h3>Step 2: The Question Data Class</h3><p>A question needs: the text being asked, the options to choose from, the index of the correct option, and a difficulty. That’s pure data — a perfect <strong>data class</strong> (Day 21):</p><pre>data class Question(<br>    val text: String,<br>    val options: List&lt;String&gt;,<br>    val correctIndex: Int,<br>    val difficulty: Difficulty<br>)</pre><p>A few design notes:</p><ul><li>options is a List&lt;String&gt; (Day 14) — the possible answers</li><li>correctIndex is the position of the right answer in that list, <strong>0-based</strong> (so the first option is index 0)</li><li>difficulty uses the enum we just made</li></ul><p>Let’s add a tiny computed property (Day 19) so a question can tell you its own correct answer text:</p><pre>data class Question(<br>    val text: String,<br>    val options: List&lt;String&gt;,<br>    val correctIndex: Int,<br>    val difficulty: Difficulty<br>) {<br>    val correctAnswer: String<br>        get() = options[correctIndex]<br>}</pre><p>Now question.correctAnswer returns the actual text of the right option, computed on demand. The class answers questions about itself — exactly the principle from Day 19.</p><h3>Step 3: The Answer Sealed Class</h3><p>Yesterday I posed a design question: should an answer be a data class with a nullable “picked index,” or a sealed class? Let’s resolve it.</p><p>The problem with nullable: pickedIndex: Int? where null means “skipped” forces every reader of the code to <em>remember</em> that null is a magic value. That’s exactly the “string-typed state” trap from Day 22. A sealed class makes the two cases explicit and impossible to confuse:</p><pre>sealed class Answer {<br>    data class Picked(val index: Int) : Answer()<br>    object Skipped : Answer()<br>}</pre><p>Two clear variants:</p><ul><li><strong>Picked(index)</strong> — the user chose the option at this index. It’s a data class because it carries data (the index).</li><li><strong>Skipped</strong> — the user skipped. It’s an object (Day 22) because “skipped” carries no data — there’s only ever one kind of skip.</li></ul><p>Now an answer is <em>self-describing</em>. You can’t accidentally treat a skip as a pick, and the compiler will force you to handle both cases. That’s the whole point of yesterday’s design discussion paying off today.</p><h3>Step 4: The Outcome Sealed Class</h3><p>When you score a question against an answer, one of three things happened: the user got it right, got it wrong, or skipped it. Each carries different information — a perfect <strong>sealed class</strong> (Day 22):</p><pre>sealed class Outcome {<br>    abstract val question: Question</pre><pre>    data class Correct(override val question: Question) : Outcome()</pre><pre>    data class Incorrect(<br>        override val question: Question,<br>        val pickedIndex: Int<br>    ) : Outcome()</pre><pre>    data class Skipped(override val question: Question) : Outcome()<br>}</pre><p>There’s one new piece here worth explaining: <strong>abstract val question: Question</strong> at the top.</p><p>All three outcomes need to remember <em>which question</em> they’re about. Rather than repeat val question: Question in all three, we declare it once as an abstract val on the parent. Each subtype then provides it with override val question. This is the inheritance idea from Day 20 — the parent declares a requirement, the children fulfill it.</p><p>So:</p><ul><li><strong>Correct</strong> — knows its question</li><li><strong>Incorrect</strong> — knows its question <em>and</em> what the user wrongly picked</li><li><strong>Skipped</strong> — knows its question</li></ul><p>Each variant carries exactly the data it needs, no more.</p><h3>Step 5: The Core Scoring Function</h3><p>Now the brain. Given one question and one answer, produce one outcome. This is where it all comes together — a function (Day 12) using when on a sealed class (Day 22) with smart casting (Day 8):</p><pre>fun scoreOne(question: Question, answer: Answer): Outcome {<br>    return when (answer) {<br>        is Answer.Skipped -&gt; Outcome.Skipped(question)<br>        is Answer.Picked -&gt; {<br>            if (answer.index == question.correctIndex) {<br>                Outcome.Correct(question)<br>            } else {<br>                Outcome.Incorrect(question, answer.index)<br>            }<br>        }<br>    }<br>}</pre><p>Read it in plain English:</p><blockquote><em>“Look at the answer. If it’s a skip, the outcome is Skipped. If it’s a pick, compare the picked index to the correct index — if they match, it’s Correct; otherwise it’s Incorrect, recording what they picked.”</em></blockquote><p>Notice:</p><ul><li>The when (answer) is <strong>exhaustive</strong> — it handles both Skipped and Picked, the only two Answer variants. No else needed (Day 22).</li><li>Inside the is Answer.Picked branch, answer.index works directly because of <strong>smart casting</strong> — Kotlin knows answer is a Picked there, so its index field is accessible (Day 8).</li><li>The function returns one of three Outcome subtypes depending on the logic.</li></ul><h3>Step 6: Score the Whole Quiz</h3><p>scoreOne handles a single question. To score the whole quiz, we run it over every question with its matching answer. This is where collections come in:</p><pre>fun scoreQuiz(questions: List&lt;Question&gt;, answers: List&lt;Answer&gt;): List&lt;Outcome&gt; {<br>    return questions.mapIndexed { index, question -&gt;<br>        val answer = answers.getOrNull(index) ?: Answer.Skipped<br>        scoreOne(question, answer)<br>    }<br>}</pre><p>Several Phase 1 concepts firing at once here:</p><ul><li><strong>mapIndexed</strong> — like map (Day 15) but the lambda also gets the index. For each question, we transform it into an outcome.</li><li><strong>answers.getOrNull(index)</strong> — safely fetch the answer at this position (Day 14). If there is no answer at that index (the answers list is shorter than the questions list), this returns null instead of crashing.</li><li><strong>?: Answer.Skipped</strong> — the Elvis operator (Day 8). If there’s no answer for this question, treat it as a skip. This elegantly handles the “what if answers list is too short?” edge case you may have predicted in yesterday’s thinking challenge.</li></ul><p>This one function quietly solves the trickiest edge case in the whole project — mismatched list lengths — in a single clean line. That’s the payoff of three weeks of small concepts compounding.</p><h3>Step 7: Test It</h3><p>Now let’s prove the scorer works. Add a main function with some sample data:</p><pre>fun main() {<br>    val questions = listOf(<br>        Question(<br>            text = &quot;What keyword declares a read-only variable in Kotlin?&quot;,<br>            options = listOf(&quot;var&quot;, &quot;val&quot;, &quot;const&quot;, &quot;let&quot;),<br>            correctIndex = 1,<br>            difficulty = Difficulty.EASY<br>        ),<br>        Question(<br>            text = &quot;Which operator provides a default for null?&quot;,<br>            options = listOf(&quot;?.&quot;, &quot;?:&quot;, &quot;!!&quot;, &quot;==&quot;),<br>            correctIndex = 1,<br>            difficulty = Difficulty.MEDIUM<br>        ),<br>        Question(<br>            text = &quot;What does a sealed class restrict?&quot;,<br>            options = listOf(<br>                &quot;Number of instances&quot;,<br>                &quot;Where subtypes can be defined&quot;,<br>                &quot;Property visibility&quot;,<br>                &quot;Method count&quot;<br>            ),<br>            correctIndex = 1,<br>            difficulty = Difficulty.HARD<br>        )<br>    )</pre><pre>    val answers = listOf(<br>        Answer.Picked(1),   // correct<br>        Answer.Picked(2),   // incorrect (picked &quot;!!&quot;, correct is &quot;?:&quot;)<br>        Answer.Skipped      // skipped<br>    )</pre><pre>    val outcomes = scoreQuiz(questions, answers)</pre><pre>    outcomes.forEach { outcome -&gt;<br>        when (outcome) {<br>            is Outcome.Correct -&gt;<br>                println(&quot;✅ CORRECT: ${outcome.question.text}&quot;)<br>            is Outcome.Incorrect -&gt;<br>                println(&quot;❌ WRONG: ${outcome.question.text} &quot; +<br>                        &quot;(you picked &#39;${outcome.question.options[outcome.pickedIndex]}&#39;, &quot; +<br>                        &quot;answer was &#39;${outcome.question.correctAnswer}&#39;)&quot;)<br>            is Outcome.Skipped -&gt;<br>                println(&quot;⏭️  SKIPPED: ${outcome.question.text}&quot;)<br>        }<br>    }<br>}</pre><p>Run it. You should see:</p><pre>✅ CORRECT: What keyword declares a read-only variable in Kotlin?<br>❌ WRONG: Which operator provides a default for null? (you picked &#39;!!&#39;, answer was &#39;?:&#39;)<br>⏭️  SKIPPED: What does a sealed class restrict?</pre><p>🎉 <strong>The scoring engine works.</strong> It correctly identifies each outcome, and the Incorrect case even tells the user what they got wrong versus the right answer — using the data the sealed class carried.</p><p>Take a moment to appreciate what just happened. That final when (outcome) block handles all three outcome types exhaustively, smart-casts each one to access its specific data, and produces a tailored message. That’s type-safe, compiler-checked, can’t-forget-a-case code — the kind professionals write every day.</p><h3>The Full Code So Far</h3><p>Here’s everything from today, stitched together. <strong>Type it incrementally</strong> as you go through the article — but here’s the complete reference:</p><pre>enum class Difficulty {<br>    EASY, MEDIUM, HARD<br>}</pre><pre>data class Question(<br>    val text: String,<br>    val options: List&lt;String&gt;,<br>    val correctIndex: Int,<br>    val difficulty: Difficulty<br>) {<br>    val correctAnswer: String<br>        get() = options[correctIndex]<br>}</pre><pre>sealed class Answer {<br>    data class Picked(val index: Int) : Answer()<br>    object Skipped : Answer()<br>}</pre><pre>sealed class Outcome {<br>    abstract val question: Question<br>    data class Correct(override val question: Question) : Outcome()<br>    data class Incorrect(<br>        override val question: Question,<br>        val pickedIndex: Int<br>    ) : Outcome()<br>    data class Skipped(override val question: Question) : Outcome()<br>}</pre><pre>fun scoreOne(question: Question, answer: Answer): Outcome {<br>    return when (answer) {<br>        is Answer.Skipped -&gt; Outcome.Skipped(question)<br>        is Answer.Picked -&gt; {<br>            if (answer.index == question.correctIndex) {<br>                Outcome.Correct(question)<br>            } else {<br>                Outcome.Incorrect(question, answer.index)<br>            }<br>        }<br>    }<br>}</pre><pre>fun scoreQuiz(questions: List&lt;Question&gt;, answers: List&lt;Answer&gt;): List&lt;Outcome&gt; {<br>    return questions.mapIndexed { index, question -&gt;<br>        val answer = answers.getOrNull(index) ?: Answer.Skipped<br>        scoreOne(question, answer)<br>    }<br>}</pre><pre>fun main() {<br>    val questions = listOf(<br>        Question(<br>            text = &quot;What keyword declares a read-only variable in Kotlin?&quot;,<br>            options = listOf(&quot;var&quot;, &quot;val&quot;, &quot;const&quot;, &quot;let&quot;),<br>            correctIndex = 1,<br>            difficulty = Difficulty.EASY<br>        ),<br>        Question(<br>            text = &quot;Which operator provides a default for null?&quot;,<br>            options = listOf(&quot;?.&quot;, &quot;?:&quot;, &quot;!!&quot;, &quot;==&quot;),<br>            correctIndex = 1,<br>            difficulty = Difficulty.MEDIUM<br>        ),<br>        Question(<br>            text = &quot;What does a sealed class restrict?&quot;,<br>            options = listOf(<br>                &quot;Number of instances&quot;,<br>                &quot;Where subtypes can be defined&quot;,<br>                &quot;Property visibility&quot;,<br>                &quot;Method count&quot;<br>            ),<br>            correctIndex = 1,<br>            difficulty = Difficulty.HARD<br>        )<br>    )</pre><pre>    val answers = listOf(<br>        Answer.Picked(1),<br>        Answer.Picked(2),<br>        Answer.Skipped<br>    )</pre><pre>    val outcomes = scoreQuiz(questions, answers)</pre><pre>    outcomes.forEach { outcome -&gt;<br>        when (outcome) {<br>            is Outcome.Correct -&gt;<br>                println(&quot;✅ CORRECT: ${outcome.question.text}&quot;)<br>            is Outcome.Incorrect -&gt;<br>                println(&quot;❌ WRONG: ${outcome.question.text} &quot; +<br>                        &quot;(you picked &#39;${outcome.question.options[outcome.pickedIndex]}&#39;, &quot; +<br>                        &quot;answer was &#39;${outcome.question.correctAnswer}&#39;)&quot;)<br>            is Outcome.Skipped -&gt;<br>                println(&quot;⏭️  SKIPPED: ${outcome.question.text}&quot;)<br>        }<br>    }<br>}</pre><p>Save this. Tomorrow we build the report layer on top of it.</p><h3>Test Your Engine’s Robustness</h3><p>Before you finish today, poke at it — exactly the edge-case thinking from yesterday’s challenge:</p><ul><li><strong>More questions than answers:</strong> delete one answer from the answers list and re-run. The extra question(s) should come back as Skipped (thanks to the Elvis fallback). This is the edge case the engine handles automatically.</li><li><strong>More answers than questions:</strong> add an extra Answer.Picked(0) at the end. Notice it’s simply ignored — mapIndexed only iterates over the questions.</li><li><strong>All correct:</strong> make every answer match its correctIndex. Every line should print ✅.</li><li><strong>All wrong:</strong> make every pick wrong. Every line ❌, each showing the right answer.</li><li><strong>Empty quiz:</strong> set questions = emptyList(). The program should run and print nothing — no crash. (Try it.)</li></ul><p>Each test takes seconds and proves your engine is solid before we build the report on top of it tomorrow.</p><h3>💪 Today’s Practice Challenge</h3><p>You’ve got a working scorer. Extend it:</p><ol><li><strong>Add a fourth question</strong> of your own. Pick a Kotlin concept from any previous day. Run it — your new question should be scored correctly with no other code changes.</li><li><strong>Add a computed property to </strong><strong>Question</strong> called isHard: Boolean that returns true if difficulty is HARD. Use it somewhere in main.</li><li><strong>Write a function</strong> correctCount(outcomes: List&lt;Outcome&gt;): Int that returns how many outcomes are Correct. Hint: outcomes.count { it is Outcome.Correct } (Day 15 + Day 22).</li><li><strong>Write a function</strong> outcomesByDifficulty(outcomes: List&lt;Outcome&gt;): Map&lt;Difficulty, List&lt;Outcome&gt;&gt; using groupBy { it.question.difficulty }. This will be useful for tomorrow’s report.</li></ol><p><strong>Bonus challenges:</strong></p><ul><li>Add a points value to each Difficulty (e.g., EASY(1), MEDIUM(2), HARD(3) — make it an enum with a constructor like Day 22). Then a correct hard question is worth more than a correct easy one.</li><li>Make scoreOne handle a “partial credit” rule via a lambda parameter (Day 16) — scoreOne(question, answer, scoring = { ... }). This is advanced; attempt it only if you’re comfortable.</li><li>Add validation: an init block on Question (Day 19) that requires correctIndex is a valid position in options. Try creating a Question with correctIndex = 99 and watch it refuse.</li></ul><h3>🎓 Practice Beyond This Article</h3><p>No new Koans today — you have a real project to extend. The practice challenges above <em>are</em> today’s practice. Get the scorer rock-solid before tomorrow’s report layer.</p><h3>👉 Tomorrow: Day 25 — The Finale</h3><p>Tomorrow we finish the capstone <strong>and</strong> close out Phase 1. We’ll build the ScoreReport data class with computed properties, write the report-building logic using collection operations, create a beautiful formatted printer, and assemble the whole thing into a complete program. Then we’ll step back and look at how far you’ve come in 25 days — and what’s waiting in Phase 2.</p><p>It’s the biggest, most satisfying day of the series so far.</p><p><strong>See you tomorrow.</strong></p><h3>📚 Series Navigation</h3><p><strong>Previous:</strong> Day 23 — Capstone Setup <em>(link)</em> <strong>You are here:</strong> Day 24 — Capstone Build, Part 1: Data &amp; Scoring <strong>Next:</strong> Day 25 — Capstone Finale &amp; Phase 1 Wrap-Up <em>(link coming tomorrow)</em></p><p>If this article helped, a clap or share means the world. It tells Medium to surface this series to more learners.</p><h3>📊 References &amp; Further Reading</h3><ul><li><a href="https://kotlinlang.org/docs/sealed-classes.html">Official Kotlin docs — Sealed classes</a></li><li><a href="https://kotlinlang.org/docs/collection-transformations.html">Kotlin docs — Collection transformations (mapIndexed)</a></li><li><a href="https://kotlinlang.org/docs/data-classes.html">Kotlin docs — Data classes</a></li><li><a href="https://play.kotlinlang.org/koans/overview">Kotlin Koans (free beginner exercises)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70b68e7ca483" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 23: Designing Your Phase 1 Capstone — A Quiz Engine]]></title>
            <link>https://kirupakaran094.medium.com/day-23-designing-your-phase-1-capstone-a-quiz-engine-5576d6c64609?source=rss-f2f70e824880------2</link>
            <guid isPermaLink="false">https://medium.com/p/5576d6c64609</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Kirubakaran]]></dc:creator>
            <pubDate>Thu, 04 Jun 2026 02:01:03 GMT</pubDate>
            <atom:updated>2026-06-04T02:01:03.346Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kHjJiHo4gYUZ0H00EO4LAg.png" /></figure><h4>Android with Kotlin for Absolute Beginners — Day 23 of the Series</h4><h3>We’re About to Build the Biggest Thing Yet</h3><p>Twenty-two days of learning. Now we put it all together.</p><p>Over the next three days — today (Day 23), Day 24, and Day 25 — you’ll build the <strong>Phase 1 Capstone</strong>: a real Kotlin program that uses essentially every concept from the past three weeks. Functions, data classes, enums, sealed classes, collections, collection operations, lambdas, null safety, when, computed properties — all of it, working together.</p><p>Today is <strong>the design day.</strong> No coding. We’ll figure out what to build, sketch its parts, decide which Phase 1 concept each piece will use, and end with a clear blueprint ready to implement. This is exactly how professional software gets built: design first, then code.</p><p>If you’re tempted to skip ahead and start typing — don’t. Design days teach you something coding doesn’t: how to think about a program <em>before</em> it exists. That skill is worth more than any individual Kotlin feature.</p><blockquote>Honestly, the moment in any project where you decide “okay, what are the moving parts and how do they fit?” is more important than any line of code that follows. I’ve shipped projects that took weeks to code but only an hour to design — and I’ve shipped projects that took an hour to code but only because I’d already spent days designing. Today, we design.</blockquote><h3>What You’ll Do Today</h3><ul><li>✅ Understand the capstone we’re building and why</li><li>✅ Identify each major piece of it (the <strong>architecture</strong>)</li><li>✅ Map each piece to the Phase 1 concept that powers it</li><li>✅ End with a blueprint ready to implement tomorrow</li></ul><h3>The Project: A Quiz Engine</h3><p>We’re building a <strong>Quiz Engine</strong> — the kind of thing you’d find inside a real quiz app, separated from any user interface.</p><p>Why a quiz engine, specifically? Three reasons:</p><p><strong>1. It’s the right shape for everything you’ve learned.</strong> Questions are data. Answers are data. Outcomes have different variants (correct, incorrect, skipped). Scoring needs collections and lambdas. Reporting needs computed values and when ladders. Every Phase 1 concept finds a natural home.</p><p><strong>2. It mirrors how real Android apps are built.</strong> Professional apps separate the “engine” (logic) from the “UI” (screens). Today’s engine is exactly what you’d plug into an Android app’s UI in Phase 2. We’re building the brain. The face comes later.</p><p><strong>3. It’s something you could actually extend.</strong> This isn’t throwaway code. With a UI on top, you’d have a real study app. Many readers of this series will keep developing this project across Phase 2 and 3.</p><h3>What the Quiz Engine Will Do</h3><p>A quiz engine takes a few inputs:</p><ul><li><strong>A list of questions</strong> — each with the question text, possible answers, and the correct answer</li><li><strong>A list of recorded user answers</strong> — what the user actually picked for each question (or skipped)</li></ul><p>And produces:</p><ul><li><strong>A per-question outcome</strong> — was each one correct, incorrect, or skipped?</li><li><strong>A score</strong> — total correct, total possible, and a percentage</li><li><strong>A grade</strong> — letter grade based on the percentage (Day 17 territory)</li><li><strong>A breakdown</strong> — how the user did across different difficulty levels</li><li><strong>A final report</strong> — clean, readable, formatted output</li></ul><p>That’s it. Small, well-defined, and <em>useful</em>. By the end of Day 25, the same engine could power a real Android quiz app — with no changes to the engine code itself, just a UI layer added on top.</p><h3>Architecture: The Major Pieces</h3><p>A program is just a collection of cooperating pieces. Here are the pieces our quiz engine needs:</p><h3>1. Data shapes — the what</h3><p>These are the <strong>types</strong> the engine works with. Pure data, no behavior:</p><ul><li><strong>Question</strong> — the text, the difficulty, the list of options, and the index of the correct option</li><li><strong>Answer</strong> — which option the user picked (or that they skipped)</li><li><strong>Outcome</strong> — was the answer correct, incorrect (with what they picked vs the right one), or skipped?</li><li><strong>ScoreReport</strong> — the final calculated report, ready to print</li></ul><p>Which Phase 1 tool builds these? <strong>Data classes</strong> (Day 21) for the four shapes with multiple fields. <strong>Sealed class</strong> (Day 22) for Outcome, since “correct,” “incorrect,” and “skipped” each carry different information.</p><h3>2. Supporting enums — the categories</h3><p>Things with a fixed, named set of values:</p><ul><li><strong>Difficulty</strong> — EASY, MEDIUM, HARD</li><li><strong>Grade</strong> — A, B, C, F</li></ul><p><strong>Enums</strong> (Day 22) — exactly what they’re for.</p><h3>3. The engine — the how</h3><p>Pure functions and a class that turn questions + answers into outcomes and reports:</p><ul><li><strong>scoreQuestion(question, answer): Outcome</strong> — given one question and the user’s answer, return the outcome</li><li><strong>scoreQuiz(questions, answers): List&lt;Outcome&gt;</strong> — run the scorer over the full quiz</li><li><strong>buildReport(questions, outcomes): ScoreReport</strong> — compute summary stats from the outcomes</li></ul><p><strong>Functions</strong> (Days 12, 13), <strong>collection operations</strong> (Day 15), and <strong>lambdas</strong> (Day 16) do the heavy lifting here.</p><h3>4. The report printer — the presentation</h3><p>One function that takes a ScoreReport and prints it nicely. Uses:</p><ul><li><strong>String templates</strong> (Day 3)</li><li><strong>when</strong> for the status line (Day 9)</li><li><strong>Computed properties</strong> on ScoreReport (Day 19) for derived numbers like percentage and grade</li></ul><h3>5. The main runner — the orchestrator</h3><p>The main function that creates sample data, runs the engine, and prints the report. Glue code only.</p><h3>How Each Phase 1 Concept Shows Up</h3><p>Let’s make the coverage explicit. By the end of Day 25, <strong>every one of these concepts will be in the code</strong>:</p><p>Day</p><p>Concept</p><p>Where it’ll appear</p><p>3</p><p>val vs var</p><p>Throughout — almost everything is val</p><p>4</p><p>Data types</p><p>Int for scores, String for text, Boolean for flags</p><p>5</p><p>Arithmetic</p><p>Calculating percentages</p><p>6</p><p>if / else</p><p>Small decisions inside helpers</p><p>8</p><p>Null safety (?:, ?.)</p><p>Defaults for empty quizzes, safe access</p><p>9</p><p>when expressions</p><p>Picking the status message, mapping percentage → grade</p><p>10</p><p>Loops</p><p>Iterating outcomes for some calculations</p><p>12</p><p>Functions</p><p>Every operation is a small named function</p><p>13</p><p>Default &amp; named arguments</p><p>buildReport takes optional passing threshold</p><p>14</p><p>Lists, Maps</p><p>Outcomes list, grouping outcomes by difficulty</p><p>15</p><p>Collection ops (map, count, filter, groupBy)</p><p>The heart of the scorer and report</p><p>16</p><p>Lambdas</p><p>Inside every collection op</p><p>18</p><p>Classes</p><p>The engine itself</p><p>19</p><p>Computed properties</p><p>percentage, grade, passes on ScoreReport</p><p>21</p><p>Data classes</p><p>Question, Answer, ScoreReport</p><p>22</p><p>Enums</p><p>Difficulty, Grade</p><p>22</p><p>Sealed classes</p><p>Outcome: Correct | Incorrect | Skipped</p><p>That’s 17 distinct concepts. In one project. About 120 lines of code.</p><p>If on Day 1 someone had told you that in three weeks you’d be writing a layered, type-safe quiz engine using sealed classes and chained collection operations, you might have raised an eyebrow. But here you are.</p><h3>Sketching the Data Shapes</h3><p>Before tomorrow’s article, let’s at least sketch the <strong>shapes</strong> — what fields each data class will have. Don’t write code yet; just imagine the structure.</p><p><strong>Question</strong> has:</p><ul><li>A text (the question being asked)</li><li>A list of options the user can choose from</li><li>The index of the correct option (0-based)</li><li>A difficulty level</li></ul><p><strong>Answer</strong> has just one thing:</p><ul><li>The index the user picked — or a “skipped” marker</li></ul><p>We could model Answer as a regular data class with a nullable pickedIndex: Int? (null means skipped). That works, but it has the same “string-typed state” problem we discussed yesterday — null is a magic value carrying meaning. A cleaner approach: make Answer <em>itself</em> a sealed class with two variants. We’ll decide tomorrow when we write the code; today, just notice that <strong>the design decision matters</strong>, and that you can now reason about it because of what you learned yesterday.</p><p><strong>Outcome</strong> is a sealed class with three variants:</p><ul><li>Correct — carries the question</li><li>Incorrect — carries the question, the picked index, and the correct index</li><li>Skipped — carries the question</li></ul><p><strong>ScoreReport</strong> has:</p><ul><li>A list of all outcomes</li><li>And computes everything else from those (correct count, percentage, grade, etc.) using <strong>computed properties</strong></li></ul><h3>The Mental Model</h3><p>Here’s what the engine will look like, conceptually, when it runs:</p><pre>[List of Questions]   +   [List of Answers]<br>              │                 │<br>              └─────┬───────────┘<br>                    ▼<br>              scoreQuiz(...)<br>                    │<br>                    ▼<br>            [List of Outcomes]<br>                    │<br>                    ▼<br>             buildReport(...)<br>                    │<br>                    ▼<br>              ScoreReport<br>                    │<br>                    ▼<br>              printReport(...)<br>                    │<br>                    ▼<br>            (formatted output)</pre><p>Five steps. Each one is a small function. Each function does exactly one thing.</p><p>This is called a <strong>pipeline</strong> — data flowing through a chain of transformations. It’s one of the most common architectural patterns in modern software, and it’s the same shape as list.filter { ... }.map { ... }.sum() chains from Day 15. Just at a bigger scale.</p><h3>What You Should Do Today</h3><p>A few small things to set you up for tomorrow:</p><ol><li><strong>Re-read this article slowly.</strong> Mental design matters more than typing.</li><li><strong>Open the </strong><a href="https://play.kotlinlang.org/"><strong>Kotlin Playground</strong></a><strong> in a fresh tab.</strong> Have it ready for tomorrow.</li><li><strong>Optional sketch:</strong> on paper or in a notes app, write the names of the four data classes (Question, Answer, Outcome, ScoreReport) and the fields you think each should have. Don’t worry about being right — the act of sketching, even badly, locks the structure in your head.</li><li><strong>No coding today.</strong> Resist the urge. Tomorrow you’ll be glad you didn’t.</li></ol><blockquote>Design days feel slow because you’re not producing output. They’re actually the fastest days, because they save you from writing the wrong thing tomorrow.</blockquote><h3>💪 Today’s Practice Challenge</h3><p>Not a coding challenge today — a <strong>thinking challenge</strong>. Pick at least two:</p><ol><li><strong>In your notes app, sketch the data shapes.</strong> Just the names + fields. No code. Compare yours with what we ended up choosing tomorrow.</li><li><strong>Predict the bugs.</strong> Look at the architecture diagram above. Which step do you think is most likely to be buggy in your first attempt? Why? (For most people, it’s “what happens when the answers list is shorter than the questions list, or vice versa?”)</li><li><strong>Imagine extending it.</strong> What would you add to make this engine 2x more interesting? A timer? Multiple-correct-answer questions? A “hints used” counter? Pick one extension and think about which data classes would need to change.</li><li><strong>Reflect.</strong> What’s the Phase 1 concept you understood least well? Today is a great time to skim that day’s article one more time before tomorrow’s build.</li></ol><h3>👉 Tomorrow: Day 24</h3><p>Tomorrow we <strong>build the engine</strong>. Data classes, sealed classes, enums, and the core scoring logic. By the end of tomorrow, you’ll have a working scorer that can take a list of questions and answers and return a list of outcomes — half the project done. Day 25 finishes it: the report, the printer, and the final assembly.</p><p>If today felt slow, tomorrow will feel fast.</p><p><strong>See you tomorrow.</strong></p><h3>📚 Series Navigation</h3><p><strong>Previous:</strong> Day 22 — Enums &amp; Sealed Classes <em>(link)</em> <strong>You are here:</strong> Day 23 — Capstone Setup: Designing the Quiz Engine <strong>Next:</strong> Day 24 — Capstone Build, Part 1 <em>(link coming tomorrow)</em></p><p>If this article helped, a clap or share means the world. It tells Medium to surface this series to more learners.</p><h3>📊 References &amp; Further Reading</h3><ul><li><a href="https://kotlinlang.org/docs/idioms.html">Official Kotlin docs — Idioms (useful patterns reference)</a></li><li><a href="https://kotlinlang.org/docs/coding-conventions.html">Kotlin docs — Coding conventions (how pros structure Kotlin)</a></li><li><a href="https://play.kotlinlang.org/koans/overview">Kotlin Koans (free beginner exercises)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5576d6c64609" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 22: Enums & Sealed Classes — Modeling “One Of These Things”]]></title>
            <link>https://kirupakaran094.medium.com/day-22-enums-sealed-classes-modeling-one-of-these-things-3353f22a1f2d?source=rss-f2f70e824880------2</link>
            <guid isPermaLink="false">https://medium.com/p/3353f22a1f2d</guid>
            <category><![CDATA[enum]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Kirubakaran]]></dc:creator>
            <pubDate>Wed, 03 Jun 2026 01:41:00 GMT</pubDate>
            <atom:updated>2026-06-03T01:41:00.708Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IEV7ouJESy1MbFp-IeanYQ.png" /></figure><h4>Android with Kotlin for Absolute Beginners — Day 22 of the Series</h4><h3>A Pattern You’ve Been Working Around</h3><p>For 21 days you’ve represented choices with strings. Day 17’s gradeFor function returned &quot;A&quot;, &quot;B&quot;, &quot;C&quot;, or &quot;F&quot; — all just String values. Day 11’s habit tracker returned status messages like &quot;🔥 You&#39;re on fire&quot; based on a percentage.</p><p>It works. But there’s a problem hiding in plain sight: <strong>the compiler can’t help you.</strong></p><p>If you typo &quot;B&quot; as &quot;b&quot; somewhere, the program won’t crash — it’ll silently behave wrong. If a function takes a String parameter “describing the loading state,” nothing stops a caller from passing &quot;banana&quot;. You’re representing a <em>fixed set of choices</em> using a type (String) that can hold <em>any</em> value. That mismatch is where bugs hide.</p><p>Today we fix that with two tools designed for exactly this problem: <strong>enums</strong> for a fixed list of named values, and <strong>sealed classes</strong> for a fixed set of “kinds of things” that can each carry their own data. Both turn runtime confusion into compile-time clarity, and both pair beautifully with the when expression you learned on Day 9.</p><blockquote>These are two of the most loved features in modern Kotlin. They sound abstract but they fix a real class of bugs I used to ship constantly in earlier languages. If your code currently uses strings to represent “states” or “types,” today’s article will probably change how you write the next month of code.</blockquote><h3>What You’ll Learn Today</h3><ul><li>✅ Enums — a fixed set of named values</li><li>✅ Adding properties and methods to enum values</li><li>✅ Sealed classes — a fixed set of <em>types</em>, each with its own data</li><li>✅ The “exhaustive when&quot; superpower</li><li>✅ When to reach for an enum vs a sealed class</li></ul><h3>Part 1: Enums</h3><h3>The Simplest Form</h3><p>An <strong>enum</strong> (short for “enumeration”) is a type with a fixed, named list of possible values. Here’s the simplest version:</p><pre>enum class Direction {<br>    NORTH, SOUTH, EAST, WEST<br>}</pre><pre>fun main() {<br>    val heading = Direction.NORTH<br>    println(heading)         // NORTH<br>    println(heading.name)    // NORTH<br>}</pre><p>Open the <a href="https://play.kotlinlang.org/">Kotlin Playground</a> and try it.</p><p>A few things to notice:</p><ul><li>enum class Direction declares a new type</li><li>NORTH, SOUTH, EAST, WEST are the <strong>only</strong> values a Direction can ever hold. There is no fifth option.</li><li>By convention, enum values are written in <strong>UPPER_CASE</strong>, like constants</li><li>Every enum value has a built-in .name property (returns &quot;NORTH&quot;)</li></ul><p>The win is in the type system: a function declared as fun move(direction: Direction) <strong>can only be called with one of those four values.</strong> You can’t pass &quot;north&quot; (a string), you can’t pass 42, you can’t pass null. The compiler enforces it.</p><h3>Enums with when — The Magic Pairing</h3><p>Here’s where enums shine. Combine them with when and Kotlin starts catching bugs <em>at compile time</em>:</p><pre>enum class Direction { NORTH, SOUTH, EAST, WEST }</pre><pre>fun describe(d: Direction): String = when (d) {<br>    Direction.NORTH -&gt; &quot;Heading up&quot;<br>    Direction.SOUTH -&gt; &quot;Heading down&quot;<br>    Direction.EAST  -&gt; &quot;Heading right&quot;<br>    Direction.WEST  -&gt; &quot;Heading left&quot;<br>}</pre><pre>fun main() {<br>    println(describe(Direction.NORTH))   // Heading up<br>    println(describe(Direction.WEST))    // Heading left<br>}</pre><p>Run it. Notice something important: <strong>there’s no </strong><strong>else branch in the </strong><strong>when.</strong> Normally, using when as an expression requires else (Day 9 rule). But with an enum, Kotlin already knows all the possible values — and as long as you cover every one, no else is needed.</p><p>This is called an <strong>exhaustive </strong><strong>when</strong>. It’s a small thing with huge consequences:</p><blockquote><em>If you ever </em><strong><em>add a fifth direction</em></strong><em>, every </em><em>when block that handled </em><em>Direction will </em>immediately<em> fail to compile until you add a branch for it.</em></blockquote><p>That’s a feature, not a bug. The compiler is forcing you to think: <em>“you added a new case — where else does that case need handling?”</em> In real Android code, this single feature has caught me countless “oh, I forgot to handle that screen state” bugs before they shipped.</p><h3>Enums with Properties and Methods</h3><p>Enum values can carry their own data and behavior. This is where enums get genuinely powerful:</p><pre>enum class Direction(val degrees: Int) {<br>    NORTH(0),<br>    EAST(90),<br>    SOUTH(180),<br>    WEST(270);</pre><pre>    fun opposite(): Direction = when (this) {<br>        NORTH -&gt; SOUTH<br>        SOUTH -&gt; NORTH<br>        EAST  -&gt; WEST<br>        WEST  -&gt; EAST<br>    }<br>}</pre><pre>fun main() {<br>    println(Direction.NORTH.degrees)       // 0<br>    println(Direction.NORTH.opposite())    // SOUTH<br>}</pre><p>A few new things:</p><ul><li>The enum class has a <strong>constructor</strong> — (val degrees: Int) — just like a regular class</li><li>Each value passes its own value into that constructor: NORTH(0), EAST(90), etc.</li><li>There’s a <strong>semicolon</strong> after the last value (WEST(270);) — that’s required when there are methods after the values</li><li>Methods live below the enum values. Inside them, this refers to whichever enum value the method is being called on</li><li>The when inside opposite() doesn’t need else because every value of Direction is covered — exhaustive again</li></ul><p>This pattern — enum values carrying related data and behavior — comes up constantly in Android development. Think enum class LogLevel(val priority: Int) { DEBUG(0), INFO(1), WARNING(2), ERROR(3) }. The values know things about themselves.</p><h3>Built-in Helpers</h3><p>Every enum class gets a couple of useful methods for free:</p><pre>val all = Direction.values()      // Array of all values, in declaration order<br>for (d in Direction.values()) {<br>    println(d)<br>}</pre><pre>val parsed = Direction.valueOf(&quot;NORTH&quot;)    // Get the value by its name string<br>println(parsed)                            // NORTH<br>// Direction.valueOf(&quot;nope&quot;)  // 💥 Throws IllegalArgumentException</pre><p>values() returns every enum value as an array — useful for iterating. valueOf(&quot;...&quot;) parses a string back into an enum value, but throws if the string doesn’t match.</p><blockquote>Pro tip: in modern Kotlin, you can also use Direction.entries instead of values() — it returns a List instead of an Array, which integrates better with collection operations like map and filter. Either works; entries is slightly nicer for new code.</blockquote><h3>Part 2: Sealed Classes</h3><p>Enums are perfect for a fixed list of <em>named values</em>. But sometimes the choices aren’t just labels — they each carry <strong>different data</strong>.</p><p>Imagine a network result. It could be:</p><ul><li><strong>Loading</strong> — no data yet, just a “wait” signal</li><li><strong>Success</strong> — carries the actual data (a user object, an article, etc.)</li><li><strong>Error</strong> — carries an error message and maybe an error code</li></ul><p>These aren’t four equivalent labels — they’re three <em>fundamentally different shapes of data</em>. An enum can’t model that cleanly. A regular String field telling you “which one” loses the type information for the data. What you need is a <strong>sealed class</strong>.</p><h3>The Basic Shape</h3><pre>sealed class NetworkResult {<br>    object Loading : NetworkResult()<br>    data class Success(val data: String) : NetworkResult()<br>    data class Error(val message: String, val code: Int) : NetworkResult()<br>}</pre><p>Three new things going on:</p><ul><li><strong>sealed class NetworkResult</strong> — declares a parent type. The sealed keyword means “the only subtypes of this class are defined right here, in this file.”</li><li><strong>object Loading</strong> — an object is a “single instance” — there’s only ever one Loading, since it carries no data. It’s Kotlin’s built-in way to express a singleton. We’ve informally seen object before; this is its first formal appearance.</li><li><strong>data class Success(val data: String)</strong> and <strong>data class Error(...)</strong> — these inherit from NetworkResult but each carries its own fields. Day 21’s data class pays off here.</li></ul><p>Now we can describe a network result with <strong>one type that has three concrete shapes</strong>:</p><pre>fun fetchUser(id: Int): NetworkResult {<br>    // Imagine real network logic here<br>    return NetworkResult.Success(&quot;User #$id: Anuki&quot;)<br>}</pre><pre>fun main() {<br>    val result: NetworkResult = fetchUser(42)</pre><pre>    when (result) {<br>        is NetworkResult.Loading -&gt; println(&quot;Still loading...&quot;)<br>        is NetworkResult.Success -&gt; println(&quot;Got data: ${result.data}&quot;)<br>        is NetworkResult.Error   -&gt; println(&quot;Failed: ${result.message} (code ${result.code})&quot;)<br>    }<br>}</pre><p>Notice three things about that when:</p><ol><li><strong>is NetworkResult.Loading</strong> — the is operator checks the type. (You met is briefly in Day 8’s smart casts.)</li><li><strong>Inside each branch, Kotlin “smart casts” </strong><strong>result</strong> — in the Success branch, you can access result.data directly without any explicit casting, because Kotlin knows from the is check that result is specifically a Success there. Same for result.message in the Error branch.</li><li><strong>No </strong><strong>else needed.</strong> Sealed classes give you the same exhaustive when superpower as enums. The compiler knows all three subtypes are defined in this one file, and forces you to handle every one.</li></ol><p>That last point is the <em>whole reason sealed classes exist.</em> They give you the safety of enums with the flexibility of carrying different data per case.</p><h3>Why “Sealed”?</h3><p>The word sealed describes the key restriction: <strong>all subtypes must be defined in the same file as the sealed class itself.</strong> No one outside this file can add a new subtype.</p><p>That’s what makes exhaustive when work. Kotlin can look at the whole file, see exactly which subtypes exist, and verify your when handles all of them. If new subtypes could appear later in some other file, the compiler couldn’t make that guarantee.</p><blockquote>In real Android code, sealed classes are the standard way to model UI state. A screen might have a sealed class UiState { object Loading; data class Content(...); data class Empty(val message); data class Error(val cause) }. The view layer pattern-matches on the current state and renders accordingly. It’s clean, type-safe, and impossible to forget a case.</blockquote><h3>Sealed Classes vs Enums Side-by-Side</h3><p>A quick comparison to lock the distinction in:</p><p><strong>Enum</strong></p><p><strong>Sealed class</strong></p><p>Fixed set of choices?</p><p>✅ Yes</p><p>✅ Yes</p><p>Each value can carry different data?</p><p>❌ All values share the same shape</p><p>✅ Each subtype has its own fields</p><p>Multiple instances per “value”?</p><p>❌ Each value is a single instance</p><p>✅ Subtypes (especially data classes) can have many instances with different data</p><p>Exhaustive when?</p><p>✅ Yes</p><p>✅ Yes</p><p>Good for…</p><p>Pure labels: directions, log levels, days of the week</p><p>Variant data: states, results, events</p><p>The cleanest mental model:</p><blockquote><strong><em>Enum</em></strong><em> = a list of </em>labels<em>. </em><strong><em>Sealed class</em></strong><em> = a list of </em>shapes<em>, where each shape carries its own data.</em></blockquote><p>If you only need labels, use enum (less ceremony). If each case carries different data, use sealed class.</p><h3>A Real Example: A Tiny State Machine</h3><p>Let’s tie it all together with something concrete. We’ll model a simple traffic light using an enum, plus a UI state using a sealed class:</p><pre>enum class LightColor(val durationSeconds: Int) {<br>    RED(30),<br>    YELLOW(5),<br>    GREEN(25);</pre><pre>    fun next(): LightColor = when (this) {<br>        RED    -&gt; GREEN<br>        GREEN  -&gt; YELLOW<br>        YELLOW -&gt; RED<br>    }<br>}</pre><pre>sealed class TrafficScreenState {<br>    object Loading : TrafficScreenState()<br>    data class Showing(val light: LightColor) : TrafficScreenState()<br>    data class Error(val reason: String) : TrafficScreenState()<br>}</pre><pre>fun render(state: TrafficScreenState) {<br>    when (state) {<br>        is TrafficScreenState.Loading -&gt; println(&quot;⏳ Loading traffic light status...&quot;)<br>        is TrafficScreenState.Showing -&gt; println(&quot;🚦 Current: ${state.light} (${state.light.durationSeconds}s)&quot;)<br>        is TrafficScreenState.Error   -&gt; println(&quot;⚠️  Couldn&#39;t fetch: ${state.reason}&quot;)<br>    }<br>}</pre><pre>fun main() {<br>    val states = listOf(<br>        TrafficScreenState.Loading,<br>        TrafficScreenState.Showing(LightColor.GREEN),<br>        TrafficScreenState.Error(&quot;No network&quot;),<br>        TrafficScreenState.Showing(LightColor.GREEN.next())<br>    )</pre><pre>    states.forEach { render(it) }<br>}<br></pre><p>Output:</p><pre>⏳ Loading traffic light status...<br>🚦 Current: GREEN (25s)<br>⚠️  Couldn&#39;t fetch: No network<br>🚦 Current: YELLOW (5s)</pre><p>In ~30 lines you’ve modeled:</p><ul><li>A fixed set of traffic light colors with their durations (enum)</li><li>A finite set of UI screen states, each carrying its own data (sealed class)</li><li>A rendering function that handles every possible state safely (exhaustive when)</li></ul><p>This shape — enum + sealed class + when — is the modern Kotlin/Android way to model “things that can be in one of several specific states.” It’s also the foundation of how modern UI frameworks (like Jetpack Compose, which we cover in Phase 3) think about screens.</p><h3>Common Mistakes Beginners Make</h3><h3>❌ Mistake 1: Using strings for fixed choices</h3><pre>fun setStatus(status: String) {       // ❌ &quot;Active&quot;? &quot;active&quot;? &quot;ACT&quot;? &quot;banana&quot;?<br>    if (status == &quot;active&quot;) { ... }<br>}</pre><pre>enum class Status { ACTIVE, PAUSED, ARCHIVED }<br>fun setStatus(status: Status) {       // ✅ Only these three are allowed<br>}</pre><h3>❌ Mistake 2: Forgetting the semicolon after enum values when adding methods</h3><pre>enum class Color {<br>    RED, GREEN, BLUE<br>    fun hex(): String = ...    // ❌ Missing semicolon after BLUE</pre><pre>    RED, GREEN, BLUE;<br>    fun hex(): String = ...    // ✅<br>}</pre><h3>❌ Mistake 3: Treating sealed classes like enums (forgetting is)</h3><pre>when (state) {<br>    NetworkResult.Loading -&gt; ...           // ⚠️ Works for the `object`...<br>    NetworkResult.Success -&gt; ...           // ❌ Error — Success is a data class, not a single instance<br>    is NetworkResult.Success -&gt; ...        // ✅ Use `is` for data class subtypes<br>}</pre><p>Use is with sealed class subtypes that have data; you can omit is only for object subtypes (which are singletons).</p><h3>❌ Mistake 4: Putting sealed subtypes in a separate file</h3><pre>// File1.kt<br>sealed class Animal</pre><pre>// File2.kt<br>class Dog : Animal()         // ⚠️ Used to be illegal; modern Kotlin allows this<br>                              // but only within the same MODULE</pre><p>Modern Kotlin (1.5+) loosened this — subtypes can be in <em>the same module</em> now, not strictly the same file. For your purposes, keep them in the same file. It’s simpler and matches what most tutorials show.</p><h3>❌ Mistake 5: Forgetting that enums and sealed classes both make when exhaustive</h3><pre>fun handle(d: Direction) {<br>    when (d) {<br>        Direction.NORTH -&gt; ...<br>        Direction.SOUTH -&gt; ...<br>        // ⚠️ Missing EAST and WEST<br>        // Kotlin won&#39;t compile if this is an expression (val x = when (d) { ... })<br>        // But as a STATEMENT (no return value used), it&#39;ll silently compile.<br>    }<br>}</pre><p>To get the full exhaustive-checking benefit, <strong>use </strong><strong>when as an expression</strong> (assign its result to a variable, or use it as a return value). Statement-form when is more lenient.</p><h3>💪 Today’s Practice Challenge</h3><p>Build a small <strong>task tracker</strong> combining everything.</p><pre>enum class Priority(val label: String, val sortOrder: Int) {<br>    HIGH(&quot;🔴 High&quot;, 0),<br>    MEDIUM(&quot;🟡 Medium&quot;, 1),<br>    LOW(&quot;🟢 Low&quot;, 2);<br>}</pre><pre>sealed class TaskState {<br>    object Pending : TaskState()<br>    data class InProgress(val percentComplete: Int) : TaskState()<br>    object Done : TaskState()<br>    data class Blocked(val reason: String) : TaskState()<br>}</pre><pre>data class Task(<br>    val title: String,<br>    val priority: Priority,<br>    val state: TaskState<br>)</pre><pre>fun summarize(task: Task): String {<br>    // Your code:<br>    // Use a when on task.state to produce a one-line summary like:<br>    //   &quot;[🔴 High] Submit report — In Progress (40%)&quot;<br>    //   &quot;[🟢 Low] Buy groceries — Pending&quot;<br>    //   &quot;[🟡 Medium] Fix bug #42 — Blocked (Waiting for design review)&quot;<br>    //   &quot;[🔴 High] Write blog post — Done ✅&quot;<br>    return &quot;&quot;<br>}</pre><pre>fun main() {<br>    val tasks = listOf(<br>        Task(&quot;Submit report&quot;, Priority.HIGH, TaskState.InProgress(40)),<br>        Task(&quot;Buy groceries&quot;, Priority.LOW, TaskState.Pending),<br>        Task(&quot;Fix bug #42&quot;, Priority.MEDIUM, TaskState.Blocked(&quot;Waiting for design review&quot;)),<br>        Task(&quot;Write blog post&quot;, Priority.HIGH, TaskState.Done)<br>    )</pre><pre>    tasks.forEach { println(summarize(it)) }<br>}</pre><p><strong>Bonus challenges:</strong></p><ul><li>Sort the tasks by priority before printing (hint: sortedBy { it.priority.sortOrder })</li><li>Use Day 15 collection operations: count how many tasks are Done, Pending, Blocked. You’ll need count { it.state is TaskState.Done } etc.</li><li>Add a method to Priority called isUrgent(): Boolean that returns true for HIGH only</li><li><strong>Stretch:</strong> Add a fourth TaskState — Cancelled(val cancelledBy: String). Notice how the compiler immediately complains about every when block that handled TaskState — and you go fix them all. That’s exhaustive when saving you from forgotten cases.</li></ul><h3>🎓 Practice Beyond This Article</h3><p>The <a href="https://kotlinlang.org/docs/sealed-classes.html"><strong>Kotlin docs on sealed classes</strong></a> have several short examples worth reading. They’re the closest official source for “this is the modern way to model variant data in Kotlin.”</p><h3>👉 Tomorrow: Day 23</h3><p>For 22 days you’ve built up Kotlin step by step, designed for absolute beginners. Tomorrow’s article is different — it’s a <strong>bridge article</strong> for developers who already know some other language (JavaScript, Python, Java, Dart) and want to fast-track their way into Kotlin without slogging through every previous day. It compresses Phase 1 into one focused article. If you’re an absolute beginner, you can skip it — it’s not for you. If you came from another language, it’ll be the article you wish you’d had on Day 1.</p><p><strong>See you tomorrow.</strong></p><h3>📚 Series Navigation</h3><p><strong>Previous:</strong> Day 21 — Data Classes <em>(link)</em> <strong>You are here:</strong> Day 22 — Enums &amp; Sealed Classes <strong>Next:</strong> Day 23 — Kotlin Fast-Track for Existing Developers <em>(link coming tomorrow)</em></p><p>If this article helped, a clap or share means the world. It tells Medium to surface this series to more learners.</p><h3>📊 References &amp; Further Reading</h3><ul><li><a href="https://kotlinlang.org/docs/enum-classes.html">Official Kotlin docs — Enum classes</a></li><li><a href="https://kotlinlang.org/docs/sealed-classes.html">Kotlin docs — Sealed classes</a></li><li><a href="https://kotlinlang.org/docs/control-flow.html#when-expression">Kotlin docs — when expression with sealed classes</a></li><li><a href="https://play.kotlinlang.org/koans/overview">Kotlin Koans (free beginner exercises)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3353f22a1f2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 21: Data Classes — One Keyword, Five Free Features]]></title>
            <link>https://kirupakaran094.medium.com/day-21-data-classes-one-keyword-five-free-features-e5278aabb33d?source=rss-f2f70e824880------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5278aabb33d</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[kotlin-data-class]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Kirubakaran]]></dc:creator>
            <pubDate>Tue, 02 Jun 2026 01:36:00 GMT</pubDate>
            <atom:updated>2026-06-02T01:36:00.700Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ifhBEpamWVpqZKbmIgd1mQ.png" /></figure><h4>Android with Kotlin for Absolute Beginners — Day 21 of the Series</h4><h3>The Day Kotlin Stops Asking You to Repeat Yourself</h3><p>For three days now you’ve been writing classes. You’ve defined properties. You’ve added getters. You’ve inherited and implemented interfaces. Real progress.</p><p>But you’ve also been hitting a quiet frustration. Remember on Day 18 when I told you println(student) would print something like Student@5e91993f — a useless memory address? Remember when comparing two students with == didn’t actually compare their fields? Remember the awkward boilerplate for making a copy of an object with one small change?</p><p>Today, one keyword fixes all of that.</p><p>The data keyword. Add it in front of class, and Kotlin generates <strong>five features for free</strong> — features that, in older languages, you’d write dozens of lines to produce manually. Once you’ve used data classes, going back to regular classes for “data-shaped” objects feels like cooking without salt.</p><p>This article is lighter than the past few. By design. After Day 19 and Day 20 — both substantial — Day 21 is your reward.</p><blockquote>Data classes are one of those Kotlin features that other languages have spent years catching up to. Java now has “records,” Swift has structs, Python has dataclasses — but Kotlin had this cleanly years before. Coming from Flutter, where I had to use code generation tools to get similar features, the built-in data keyword still feels like a luxury.</blockquote><h3>What You’ll Learn Today</h3><ul><li>✅ The data keyword and what it generates for you</li><li>✅ A clean toString() for free</li><li>✅ Sensible equals() and hashCode() for free</li><li>✅ The copy() method for making modified versions</li><li>✅ Destructuring declarations</li><li>✅ When to use data class vs regular class</li></ul><h3>The Problem We’re Solving</h3><p>Here’s a regular class, like the ones you wrote on Day 18:</p><pre>class Student(val name: String, val score: Int)</pre><pre>fun main() {<br>    val a = Student(&quot;Anuki&quot;, 95)<br>    val b = Student(&quot;Anuki&quot;, 95)</pre><pre>    println(a)            // Student@5e91993f  (useless memory address)<br>    println(a == b)       // false  (same data, but Kotlin says they&#39;re different!)<br>}</pre><p>Open the <a href="https://play.kotlinlang.org/">Kotlin Playground</a> and run it. You’ll see exactly that output — and both lines are problems.</p><p><strong>The first problem:</strong> Kotlin doesn’t know how to print a Student. So it falls back to the type name + a memory address. Useless.</p><p><strong>The second problem:</strong> Kotlin compares a == b by checking <em>if they’re literally the same object in memory</em> — not by their data. Two different Student objects with identical name and score are considered “not equal.”</p><p>Now watch what happens when we add one tiny keyword:</p><pre>data class Student(val name: String, val score: Int)</pre><pre>fun main() {<br>    val a = Student(&quot;Anuki&quot;, 95)<br>    val b = Student(&quot;Anuki&quot;, 95)</pre><pre>    println(a)            // Student(name=Anuki, score=95)  ✨<br>    println(a == b)       // true  ✨ — comparison by content, not identity<br>}</pre><p>Same code. One word added. Two problems fixed. <em>And</em> three more features unlocked. Let’s see what data actually gives you.</p><h3>What data Gives You — Free of Charge</h3><p>When you mark a class as data, Kotlin automatically generates <strong>five things</strong> based on the constructor properties:</p><ol><li><strong>A useful </strong><strong>toString()</strong> — Student(name=Anuki, score=95)</li><li><strong>A content-aware </strong><strong>equals()</strong> — a == b compares property values</li><li><strong>A matching </strong><strong>hashCode()</strong> — needed for sets and maps to work correctly</li><li><strong>A </strong><strong>copy() method</strong> — for making modified copies</li><li><strong>componentN() methods</strong> — enabling destructuring</li></ol><p>You don’t write any of these. You don’t see them. They just appear, derived from the properties you listed in the constructor. Let’s walk through each one.</p><h3>1. A Useful toString()</h3><p>toString() is what Kotlin calls when you use a value inside a string template or println. Regular classes have a toString() inherited from the base Any class — and that default is unhelpful. Data classes generate a sensible one:</p><pre>data class User(val name: String, val email: String, val age: Int)</pre><pre>fun main() {<br>    val u = User(&quot;Kiruba&quot;, &quot;k@example.com&quot;, 25)<br>    println(u)<br>    // User(name=Kiruba, email=k@example.com, age=25)</pre><pre>    println(&quot;Got user: $u&quot;)<br>    // Got user: User(name=Kiruba, email=k@example.com, age=25)<br>}</pre><p>That’s it. Every property listed, in order, formatted readably. Perfect for debugging, logging, and quick inspection.</p><blockquote>In Android development, when you log something or print to the console, you want to see the actual contents — not a memory address. Data classes give you that for free. Every time I’m tempted to write a custom toString(), I check first: should this just be a data class instead? Usually, yes.</blockquote><h3>2. Content-Aware equals() and hashCode()</h3><p>equals() is what == uses behind the scenes. For regular classes, two objects are equal <strong>only if they’re the literal same object in memory</strong>:</p><pre>class Point(val x: Int, val y: Int)</pre><pre>val a = Point(1, 2)<br>val b = Point(1, 2)<br>println(a == b)   // false — different objects in memory</pre><p>Data classes fix this by comparing property values:</p><pre>data class Point(val x: Int, val y: Int)</pre><pre>val a = Point(1, 2)<br>val b = Point(1, 2)<br>println(a == b)   // true — same property values</pre><p>This is almost always what you actually want when you compare data. Two Student(&quot;Anuki&quot;, 95) objects <em>should</em> be considered equal.</p><p>hashCode() is a related method that goes hand-in-hand with equals(). You don’t usually call it directly, but it’s what makes Set and Map work correctly:</p><pre>data class User(val id: Int, val name: String)</pre><pre>val users = setOf(<br>    User(1, &quot;Anuki&quot;),<br>    User(1, &quot;Anuki&quot;),       // same data — Set deduplicates this away<br>    User(2, &quot;Kiruba&quot;)<br>)<br>println(users.size)   // 2, not 3 — Set saw the duplicate</pre><p>Without data, the set wouldn’t know to deduplicate — it’d think each User was unique. Data classes make collections behave the way you’d expect.</p><h3>3. The copy() Method</h3><p>This one is special. Often you have an object and want to create a <em>modified version</em> of it — same as the original except for one or two changes. Without data classes, you’d manually construct a new object with all the original values plus the changes. With data classes, Kotlin gives you copy():</p><pre>data class User(val name: String, val email: String, val isActive: Boolean)</pre><pre>fun main() {<br>    val original = User(&quot;Kiruba&quot;, &quot;k@old.com&quot;, isActive = true)</pre><pre>    val withNewEmail = original.copy(email = &quot;k@new.com&quot;)<br>    val deactivated = original.copy(isActive = false)</pre><pre>    println(original)       // User(name=Kiruba, email=k@old.com, isActive=true)<br>    println(withNewEmail)   // User(name=Kiruba, email=k@new.com, isActive=true)<br>    println(deactivated)    // User(name=Kiruba, email=k@old.com, isActive=false)<br>}</pre><p>copy(...) takes <strong>named arguments</strong> (Day 13 again!) for any properties you want to change. Everything else is taken from the original.</p><p>Notice the original is <strong>untouched.</strong> copy() returns a <em>new</em> object — the original User still has the old email. This is the key idea of <strong>immutable data</strong>: instead of mutating an existing object, you create a new one with the changes you want.</p><blockquote>This pattern is everywhere in modern Android development, especially in apps using Jetpack Compose (Phase 3 material). The whole “state management” approach in Compose is built on copy()-style updates of immutable data classes. When we get there in two weeks, you’ll already understand it.</blockquote><h3>4. Destructuring Declarations</h3><p>You met this on Day 10 with withIndex() and Day 14 with Map. Data classes are what makes it work — and now you can use destructuring on <strong>your own</strong> classes too:</p><pre>data class User(val name: String, val email: String, val age: Int)</pre><pre>fun main() {<br>    val u = User(&quot;Kiruba&quot;, &quot;k@example.com&quot;, 25)</pre><pre>    val (name, email, age) = u<br>    println(name)    // Kiruba<br>    println(email)   // k@example.com<br>    println(age)     // 25<br>}</pre><p>The val (name, email, age) = u line pulls out the properties <strong>in their constructor order</strong> and assigns each to a variable. It’s a clean way to unpack data when you want all (or most) of the fields locally.</p><p>A practical example — iterating a list of users:</p><pre>val users = listOf(<br>    User(&quot;Anuki&quot;, &quot;a@x.com&quot;, 30),<br>    User(&quot;Sahan&quot;, &quot;s@x.com&quot;, 22)<br>)</pre><pre>for ((name, _, age) in users) {<br>    println(&quot;$name is $age&quot;)<br>}</pre><p>Notice the _ for the email. That’s “ignore this one” — useful when you don’t need every property.</p><p>⚠️ One important caveat: <strong>destructuring matches by position, not name.</strong> That makes refactoring risky — if you change the constructor order of your data class, every val (a, b, c) = ... line elsewhere now has its values shuffled. Use destructuring for small, stable data classes; for big ones, access by property name is safer.</p><h3>5. componentN() Methods (Mostly Behind the Scenes)</h3><p>This is the <em>why</em> behind destructuring. Data classes generate methods called component1(), component2(), etc., one per property:</p><pre>data class User(val name: String, val email: String)</pre><pre>val u = User(&quot;Kiruba&quot;, &quot;k@example.com&quot;)<br>println(u.component1())   // Kiruba<br>println(u.component2())   // k@example.com</pre><p>You’ll almost never call these directly — destructuring is the human-friendly syntax for them. But it’s good to know they exist; if you read advanced Kotlin code, occasionally you’ll see them spelled out.</p><h3>A Real Refactor: Yesterday’s Code with Data Classes</h3><p>Remember the MediaItem example from Day 20? Let’s revisit a piece of it. Even though MediaItem is meant to be inherited (so it stays a regular open class), you can have data classes <em>inside</em> a non-data hierarchy. Or — more often — you’d model the whole thing without inheritance, using data classes:</p><pre>data class Book(val title: String, val author: String, val pages: Int)<br>data class Movie(val title: String, val runtimeMinutes: Int, val genre: String)</pre><pre>fun main() {<br>    val original = Book(&quot;Atomic Habits&quot;, &quot;James Clear&quot;, 320)<br>    println(original)</pre><pre>    val updated = original.copy(pages = 330)<br>    println(updated)</pre><pre>    val sameAsOriginal = Book(&quot;Atomic Habits&quot;, &quot;James Clear&quot;, 320)<br>    println(original == sameAsOriginal)   // true<br>}</pre><p>Look at how much you got from those two data class lines. Useful printing, content-aware equality, a copy() method, destructuring, and componentN() accessors. Easily 50 lines of boilerplate code in another language. Two lines here.</p><h3>Rules for Data Classes</h3><p>A few things data classes require — Kotlin will refuse to compile if you break them:</p><ol><li><strong>The primary constructor must have at least one parameter.</strong> Empty data classes aren’t allowed.</li><li><strong>All constructor parameters must be </strong><strong>val or </strong><strong>var.</strong> Plain parameters (no val/var) won’t work — they need to actually be properties for the generated methods to use them.</li><li><strong>Data classes can’t be </strong><strong>abstract, </strong><strong>open, </strong><strong>sealed, or </strong><strong>inner.</strong> They’re meant to be concrete, simple data holders.</li></ol><p>There’s also a more subtle rule: <strong>only properties declared in the primary constructor count for the generated methods.</strong> If you add properties in the class body, they won’t be included in equals, toString, hashCode, or copy:</p><pre>data class User(val name: String) {<br>    var lastLogin: String = &quot;never&quot;   // ⚠️ NOT part of equals/toString/copy<br>}</pre><pre>val a = User(&quot;Kiruba&quot;)<br>a.lastLogin = &quot;today&quot;<br>val b = User(&quot;Kiruba&quot;)<br>b.lastLogin = &quot;yesterday&quot;</pre><pre>println(a == b)   // true — only `name` was compared<br>println(a)        // User(name=Kiruba) — lastLogin not shown</pre><p>This is intentional. The primary constructor defines “what makes this object what it is.” Body properties are auxiliary state. But it’s a surprise the first time you see it. Most of the time, you want all the meaningful data in the constructor.</p><h3>When to Use data class vs Regular class</h3><p>A simple rule that holds up well:</p><blockquote><strong><em>If the class exists primarily to hold and pass around data — use </em></strong><strong><em>data class.</em></strong><em> </em><strong><em>If the class has substantial behavior, identity matters, or it’s meant to be inherited from — use regular </em></strong><strong><em>class.</em></strong></blockquote><p>In a typical Android app, a <em>large</em> share of your classes are data classes:</p><ul><li>API response shapes (UserDto, Article, WeatherForecast)</li><li>Database entities</li><li>UI state objects (HomeScreenState, SettingsState)</li><li>Domain models (User, Order, Message)</li><li>Event objects (ButtonClicked(val timestamp: Long))</li></ul><p>Things that are <em>not</em> good candidates for data classes:</p><ul><li>A Service or Repository that does work (has lots of methods)</li><li>Anything you want to inherit from (data classes can’t be open)</li><li>Anything where two objects with the same data should still be considered different (rare, but happens)</li></ul><blockquote>I’d estimate about 60–70% of the classes in a real Android codebase are data classes. The other 30–40% are services, repositories, view models, and the like — classes with substantial behavior. Once you internalize “this is data, that’s behavior,” choosing between the two becomes instant.</blockquote><h3>Common Mistakes Beginners Make</h3><h3>❌ Mistake 1: Forgetting that copy() doesn’t modify the original</h3><pre>val u = User(&quot;Kiruba&quot;, &quot;old@x.com&quot;)<br>u.copy(email = &quot;new@x.com&quot;)<br>println(u.email)   // still &quot;old@x.com&quot; — copy() returns a new object, we threw it away!</pre><pre>val updated = u.copy(email = &quot;new@x.com&quot;)   // ✅ store the result</pre><h3>❌ Mistake 2: Trying to inherit from a data class</h3><pre>data class Animal(val name: String)<br>class Dog : Animal(&quot;Rex&quot;)   // ❌ Error — data classes can&#39;t be open</pre><p>Data classes are final by design. Need inheritance? Use a regular class.</p><h3>❌ Mistake 3: Putting important properties in the class body</h3><pre>data class User(val name: String) {<br>    var email: String = &quot;&quot;   // ⚠️ NOT part of equals/toString/copy<br>}</pre><p>If a property matters for equality or printing, put it in the constructor.</p><h3>❌ Mistake 4: Forgetting val or var on constructor parameters</h3><pre>data class Point(x: Int, y: Int)   // ❌ Error — parameters must be properties<br>data class Point(val x: Int, val y: Int)   // ✅</pre><h3>❌ Mistake 5: Using data classes for everything</h3><pre>data class DatabaseConnection(val url: String) {<br>    fun connect() { /* lots of code */ }<br>    fun query(sql: String) { /* lots of code */ }<br>    fun close() { /* lots of code */ }<br>}</pre><p>This isn’t <em>wrong</em>, but it’s a smell. A class with significant behavior shouldn’t usually be a data class — its identity isn’t really its url property. Reach for a regular class here.</p><h3>💪 Today’s Practice Challenge</h3><p>Build a small <strong>order-management</strong> program using data classes.</p><pre>data class Product(val id: Int, val name: String, val price: Double)<br>data class Order(val id: Int, val product: Product, val quantity: Int) {<br>    // Add a computed property `total: Double` (price × quantity)<br>}</pre><pre>fun main() {<br>    val notebook = Product(1, &quot;Notebook&quot;, 8.50)<br>    val pen = Product(2, &quot;Pen&quot;, 2.00)</pre><pre>    val orders = listOf(<br>        Order(101, notebook, 3),<br>        Order(102, pen, 10),<br>        Order(103, notebook, 1),<br>        Order(104, pen, 5)<br>    )</pre><pre>    // Your tasks (use Day 15 collection operations):<br>    // 1. Print every order on its own line (data class toString helps here)<br>    // 2. Total revenue (sum of every order&#39;s total)<br>    // 3. Most-ordered product by total quantity (across all orders)<br>    // 4. Build a new order with copy() — same as order 101 but quantity 5<br>    // 5. Use destructuring inside a forEach to print just product name + quantity</pre><pre>    // Hint: orders.sumOf { it.total } for revenue<br>    // Hint: groupBy + sumOf for the most-ordered product<br>}</pre><p><strong>Bonus challenges:</strong></p><ul><li>Add a discount: Double = 0.0 parameter to Order (with a default of 0). Adjust the total calculation to apply the discount.</li><li>Try comparing two Order objects with the same data using == — confirm they’re equal. Now wrap one of them in a listOf(...) and use .contains(...) to check if the other is “in” the list. (This is exactly why equals() mattering for data is huge.)</li><li>Make a CartItem(val product: Product, var quantity: Int) (using var instead of val) — then notice how copy() still works exactly the same. var is allowed in data classes.</li><li><strong>Stretch:</strong> Build a summarize(orders: List&lt;Order&gt;): String function that returns a multi-line string with total revenue, item count, average order size, and top product. Practice combining today’s data classes with Day 15 collection operations.</li></ul><h3>🎓 Practice Beyond This Article</h3><p>The <a href="https://play.kotlinlang.org/koans/Introduction/Data%20classes/Task.kt"><strong>Kotlin Koans — Data classes</strong></a> and surrounding tasks are exactly today’s material. They take a few minutes each and are some of the most satisfying exercises in the set — you’ll see how copy() and destructuring make problems collapse.</p><h3>👉 Tomorrow: Day 22</h3><p>You’ve now got regular classes, inheritance, interfaces, and data classes. Tomorrow we round out the type-modeling story with two more tools: <strong>enums</strong> for fixed sets of named values, and <strong>sealed classes</strong> for situations like “this thing is exactly one of these specific types.” These are the tools you’ll reach for when modeling things like loading states, error types, or any “one-of-N” decision. They pair beautifully with the when expression from Day 9.</p><p><strong>See you tomorrow.</strong></p><h3>📚 Series Navigation</h3><p><strong>Previous:</strong> Day 20 — Inheritance &amp; Interfaces <em>(link)</em> <strong>You are here:</strong> Day 21 — Data Classes <strong>Next:</strong> Day 22 — Enums &amp; Sealed Classes <em>(link coming tomorrow)</em></p><p>If this article helped, a clap or share means the world. It tells Medium to surface this series to more learners.</p><h3>📊 References &amp; Further Reading</h3><ul><li><a href="https://kotlinlang.org/docs/data-classes.html">Official Kotlin docs — Data classes</a></li><li><a href="https://kotlinlang.org/docs/destructuring-declarations.html">Kotlin docs — Destructuring declarations</a></li><li><a href="https://kotlinlang.org/docs/equality.html">Kotlin docs — Equality</a></li><li><a href="https://play.kotlinlang.org/koans/Introduction/Data%20classes/Task.kt">Kotlin Koans — Data classes</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5278aabb33d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 20: Inheritance & Interfaces — Sharing Code and Defining Capabilities]]></title>
            <link>https://kirupakaran094.medium.com/day-20-inheritance-interfaces-sharing-code-and-defining-capabilities-3a9a42d6ec6f?source=rss-f2f70e824880------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a9a42d6ec6f</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[interfaces]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Kirubakaran]]></dc:creator>
            <pubDate>Mon, 01 Jun 2026 02:01:00 GMT</pubDate>
            <atom:updated>2026-06-01T02:01:00.905Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zQSLIMhANZ2qVJBoeCJz4A.png" /></figure><h4>Android with Kotlin for Absolute Beginners — Day 20 of the Series</h4><h3>The Two Big Ideas of Object-Oriented Design</h3><p>For the past two days you’ve built classes that stood completely alone. A Student was a Student. A Book was a Book. A BankAccount was a BankAccount. Each one was its own little island.</p><p>Real programs don’t work like that. In real software, classes have <strong>relationships</strong> with each other:</p><ul><li>A Dog is an Animal, and so is a Cat. They share traits — both have a name and a sound — but they’re also clearly different.</li><li>A Button and a TextField are both <strong>clickable</strong>, even though one shows text and the other accepts input. They’re not the “same kind of thing” — but they share a capability.</li></ul><p>Today we cover the two tools Kotlin gives you for these patterns: <strong>inheritance</strong> (for “is-a” relationships) and <strong>interfaces</strong> (for “can-do” capabilities).</p><p>These are two of the most powerful — and most over-used — concepts in object-oriented programming. We’ll cover what each one is, when to reach for it, and importantly, when <em>not</em> to. Used well, they make code dramatically easier to extend. Used badly, they create knots that are hard to untangle. I’ll show you both edges.</p><blockquote>Both concepts feel a little abstract on first read. They’re easier to grasp through examples than definitions. Type today’s code. Run it. Modify it. Inheritance and interfaces only really click once you’ve felt them in motion — reading about them isn’t enough.</blockquote><h3>What You’ll Learn Today</h3><ul><li>✅ Inheritance — building one class on top of another</li><li>✅ The open keyword and why Kotlin makes you opt in</li><li>✅ Overriding methods and properties</li><li>✅ Interfaces — defining capabilities</li><li>✅ Implementing multiple interfaces on one class</li><li>✅ When to use inheritance vs interfaces (the honest guide)</li></ul><h3>Inheritance: Building on What Already Exists</h3><p>Imagine you’re modeling animals. Every animal has a name and makes some kind of sound:</p><pre>class Animal(val name: String) {<br>    fun describe() {<br>        println(&quot;$name says... something.&quot;)<br>    }<br>}</pre><p>Now you want a Dog and a Cat. Both are animals — both have a name, both make sounds. You <em>could</em> write two separate classes that repeat all this code. But that’s wasteful and error-prone. Inheritance lets you say: <em>“A Dog is an Animal, but with these additions.”</em></p><p>Open the <a href="https://play.kotlinlang.org/">Kotlin Playground</a> and try:</p><pre>open class Animal(val name: String) {<br>    open fun sound(): String = &quot;some generic sound&quot;</pre><pre>    fun describe() {<br>        println(&quot;$name says ${sound()}&quot;)<br>    }<br>}</pre><pre>class Dog(name: String) : Animal(name) {<br>    override fun sound(): String = &quot;Woof!&quot;<br>}</pre><pre>class Cat(name: String) : Animal(name) {<br>    override fun sound(): String = &quot;Meow.&quot;<br>}</pre><pre>fun main() {<br>    val rex = Dog(&quot;Rex&quot;)<br>    val whiskers = Cat(&quot;Whiskers&quot;)</pre><pre>    rex.describe()        // Rex says Woof!<br>    whiskers.describe()   // Whiskers says Meow.<br>}</pre><p>There’s a lot of new syntax in there. Let’s break it all down.</p><h3>open class — Opting in to Inheritance</h3><pre>open class Animal(val name: String)</pre><p>In Kotlin, <strong>classes are closed (final) by default.</strong> You can’t inherit from a class unless its author marks it open. This is the opposite of Java, where everything is inheritable by default.</p><p>Why does Kotlin do this? Because inheritance is one of those features that’s easy to misuse. Forcing the author to opt in with open is Kotlin’s way of saying: <em>“only allow inheritance when you’ve actually thought about it.”</em></p><p>The same applies to methods and properties — they’re closed by default and need open to be overrideable.</p><h3>: Animal(name) — Declaring a Subclass</h3><pre>class Dog(name: String) : Animal(name)</pre><p>The : Animal(name) part says two things:</p><ol><li><strong>Dog inherits from </strong><strong>Animal</strong> — the colon means “extends”</li><li><strong>Animal(name)</strong> — Dog passes its name parameter into Animal&#39;s constructor</li></ol><p>That second part trips up beginners. Read it as: <em>“to build a </em><em>Dog, take a name, then build an </em><em>Animal with that name first.”</em> The parent class is constructed before the subclass adds anything new.</p><p>Notice Dog&#39;s constructor has name: String — no val. That’s because name is already a property on Animal (declared with val there). We don’t want to redeclare it; we just want to pass it through.</p><h3>override — Replacing Parent Behavior</h3><pre>class Dog(name: String) : Animal(name) {<br>    override fun sound(): String = &quot;Woof!&quot;<br>}</pre><p>override says: <em>“the parent class has a method called </em><em>sound(), and I’m replacing it with my own version.”</em></p><p>You must use override. Just defining a function with the same name as a parent’s method won’t work — Kotlin will refuse to compile. That explicitness is intentional: it prevents accidentally shadowing a parent method when you didn’t mean to.</p><p>For override to work, <strong>the parent’s method must be marked </strong><strong>open</strong>. If the parent author didn’t say open fun sound(), you can’t override it.</p><h3>What Just Happened</h3><p>When you wrote rex.describe():</p><ol><li>Kotlin called describe() on the Dog instance</li><li>Dog doesn’t define describe() — but its parent Animal does, so Kotlin uses that</li><li>Inside describe(), the call to sound() runs the Dog&#39;s overridden version, not the generic one in Animal</li><li>Result: Rex says Woof!</li></ol><p>That’s <strong>polymorphism</strong> in action — the same method (describe()) behaves differently depending on which subclass it’s called on. You don’t have to write if (animal is Dog) ... else if (animal is Cat) ... anywhere. Each class brings its own behavior with it.</p><h3>A Bigger Inheritance Example</h3><p>Let’s build something a little more substantial — a shape hierarchy:</p><pre>open class Shape(val name: String) {<br>    open fun area(): Double = 0.0<br>    open fun describe() = println(&quot;$name with area ${area()}&quot;)<br>}</pre><pre>class Circle(val radius: Double) : Shape(&quot;Circle&quot;) {<br>    override fun area(): Double = 3.14159 * radius * radius<br>}</pre><pre>class Rectangle(val width: Double, val height: Double) : Shape(&quot;Rectangle&quot;) {<br>    override fun area(): Double = width * height<br>}</pre><pre>class Square(side: Double) : Rectangle(side, side) {<br>    // No overrides needed — Rectangle&#39;s logic already works for squares<br>}</pre><pre>fun main() {<br>    val shapes = listOf(<br>        Circle(5.0),<br>        Rectangle(4.0, 6.0),<br>        Square(3.0)<br>    )</pre><pre>    shapes.forEach { it.describe() }<br>}</pre><p>Run it. Output:</p><pre>Circle with area 78.53975<br>Rectangle with area 24.0<br>Rectangle with area 9.0</pre><p>Notice:</p><ul><li>Square inherits from Rectangle, which inherits from Shape. <strong>Inheritance chains</strong> are allowed.</li><li>Square provides no overrides — it just passes the same value as both width and height to Rectangle&#39;s constructor.</li><li>The shapes list holds a Circle, a Rectangle, and a Square — <em>different types</em>, but all are Shapes. The forEach calls describe() on each, and each runs the right version of area() automatically.</li></ul><p>That last bullet is the real superpower. You can treat a list of mixed types uniformly <em>because they share a parent</em>. This is the kind of abstraction that makes real applications maintainable.</p><h3>Interfaces: Defining Capabilities</h3><p>Inheritance answers “what kind of thing is this?” Interfaces answer a different question: <strong>“what can this thing do?”</strong></p><p>Let’s say you’re building an Android app. You have a Button, an Image, a Toast, and a Menu. None of these are “the same kind of thing” — but all of them can be <em>clicked</em>.</p><p>You could:</p><ul><li>Use inheritance — create a Clickable parent class for all of them. But then Image becomes a Clickable, which is weird (an image is a thing, not a capability).</li><li>Use an <strong>interface</strong> — define Clickable as a <em>capability</em>. Any class can declare “I can do this,” regardless of what it actually is.</li></ul><p>Interfaces are exactly that — a contract that says “if you implement me, you guarantee these methods exist.” Here’s the basic shape:</p><pre>interface Clickable {<br>    fun onClick()<br>}</pre><pre>interface Hoverable {<br>    fun onHover()<br>}</pre><pre>class Button(val label: String) : Clickable, Hoverable {<br>    override fun onClick() {<br>        println(&quot;Button &#39;$label&#39; was clicked!&quot;)<br>    }</pre><pre>    override fun onHover() {<br>        println(&quot;Hovering over &#39;$label&#39;&quot;)<br>    }<br>}</pre><pre>class Image(val src: String) : Clickable {<br>    override fun onClick() {<br>        println(&quot;Image &#39;$src&#39; was clicked!&quot;)<br>    }<br>}</pre><pre>fun main() {<br>    val items: List&lt;Clickable&gt; = listOf(<br>        Button(&quot;Save&quot;),<br>        Image(&quot;logo.png&quot;)<br>    )</pre><pre>    items.forEach { it.onClick() }<br>}</pre><p>A few things to notice:</p><ul><li><strong>interface declares a capability</strong>, not a thing. It contains method signatures (no body in the simplest case).</li><li><strong>A class can implement multiple interfaces</strong> — Button is both Clickable and Hoverable. There’s no limit. (You can only inherit from <em>one</em> class but implement <em>many</em> interfaces.)</li><li><strong>Same </strong><strong>override keyword</strong> — implementing an interface method uses override, just like overriding a parent class method.</li><li><strong>Polymorphism still works</strong> — you can have a List&lt;Clickable&gt; containing different unrelated classes, and forEach calls each one’s onClick().</li></ul><p>Interfaces feel restrictive at first — they’re just empty methods, no real code. But that <em>is</em> the point. They let you treat unrelated classes as similar where it matters, without forcing them to share a parent.</p><h3>Interfaces Can Also Have Default Implementations</h3><p>Modern Kotlin interfaces aren’t <em>only</em> empty. They can provide default implementations that classes inherit unless they choose to override:</p><pre>interface Greetable {<br>    val name: String</pre><pre>    fun greet() {<br>        println(&quot;Hello, $name!&quot;)    // default implementation<br>    }<br>}</pre><pre>class Person(override val name: String) : Greetable</pre><pre>fun main() {<br>    Person(&quot;Anuki&quot;).greet()    // Hello, Anuki!<br>}</pre><p>Notice Person declares no greet() method — it inherits the default from Greetable. But it <em>does</em> have to provide name, because the interface requires it (with override val name: String in the constructor).</p><p>This blurs the line between interfaces and abstract classes a little, but it’s a useful tool. Interfaces with default implementations let you share <em>some</em> code without forcing inheritance.</p><h3>When to Use Inheritance vs Interfaces (Honest Guide)</h3><p>Here’s the heuristic I’ve seen work best in practice:</p><p>Use <strong>inheritance</strong> when…</p><p>Use <strong>interfaces</strong> when…</p><p>There’s a clear “is-a” relationship (Dog <em>is</em> an Animal)</p><p>There’s a “can-do” capability (Button <em>can be</em> clicked)</p><p>The classes share substantial state and behavior</p><p>The classes share only a contract, not the data</p><p>The hierarchy is small and unlikely to grow chaotically</p><p>Many unrelated classes need the same capability</p><p><strong>A general piece of advice</strong> that’s saved me many headaches:</p><blockquote><strong><em>Prefer interfaces over inheritance whenever you can.</em></strong></blockquote><p>That’s not a strict rule, but it’s the right default. Inheritance creates tight coupling between parent and child — when the parent changes, every child can break. Interfaces, by their nature, are looser. They demand a contract but make no promises about implementation.</p><p>Modern Kotlin code uses inheritance sparingly. You’ll see interfaces <em>everywhere</em> in real Android codebases. Things like OnClickListener, Comparable, Iterable, Runnable — all interfaces.</p><blockquote>In my own Android work, I find I write maybe one inheritance hierarchy for every 20 interfaces I define or implement. That’s not because inheritance is bad — it’s because the “this is exactly that, with a twist” pattern is rarer than it seems. Most of what looks like inheritance can be modeled more cleanly as composition + interfaces.</blockquote><p>We won’t deep-dive into “composition over inheritance” today — that’s a software-engineering principle worth a full article on its own, eventually. For now, just know that the question isn’t <em>“how do I inherit from this?”</em> It’s <em>“is inheritance the right tool here at all?”</em></p><h3>Common Mistakes Beginners Make</h3><h3>❌ Mistake 1: Forgetting open</h3><pre>class Animal(val name: String)         // ❌ can&#39;t inherit from this<br>class Dog : Animal(&quot;Rex&quot;)              // Error: Animal is final</pre><pre>open class Animal(val name: String)    // ✅ now Dog can inherit<br>class Dog : Animal(&quot;Rex&quot;)</pre><p>Kotlin requires explicit opt-in. Forget open, and the compiler will tell you immediately.</p><h3>❌ Mistake 2: Forgetting to call the parent’s constructor</h3><pre>open class Animal(val name: String)</pre><pre>class Dog : Animal          // ❌ Where&#39;s the name?<br>class Dog(name: String) : Animal(name)   // ✅ Pass it through</pre><h3>❌ Mistake 3: Forgetting override</h3><pre>open class Animal { open fun sound(): String = &quot;...&quot; }</pre><pre>class Dog : Animal() {<br>    fun sound(): String = &quot;Woof&quot;        // ❌ Error — you&#39;re hiding, not overriding<br>    override fun sound(): String = &quot;Woof&quot;   // ✅<br>}</pre><h3>❌ Mistake 4: Trying to inherit from multiple classes</h3><pre>class Dog : Animal, Pet     // ❌ Can&#39;t inherit from two classes<br>class Dog : Animal, Pet     // ✅ ONE class, MULTIPLE interfaces — Pet here would be an interface</pre><p>Kotlin (like most modern languages) allows single inheritance only. If you need traits from multiple sources, make some of them interfaces.</p><h3>❌ Mistake 5: Overusing inheritance</h3><pre>open class Vehicle<br>open class Car : Vehicle()<br>open class FourDoorCar : Car()<br>open class FourDoorSedan : FourDoorCar()<br>open class FourDoorRedSedan : FourDoorSedan()<br>// ❌ This hierarchy is going to give you nightmares</pre><p>Deep inheritance trees are almost always a sign that you’re modeling categories instead of behaviors. Reach for properties (val color, val doorCount) before more subclasses.</p><h3>💪 Today’s Practice Challenge</h3><p>Build a small <strong>media library</strong> with a mix of inheritance and interfaces.</p><p>Requirements:</p><ol><li>An open class MediaItem with a title: String and an open fun describe() method that prints &quot;&lt;Title&gt;&quot;</li><li>A Book subclass that adds author: String and overrides describe() to also include the author</li><li>A Movie subclass that adds runtimeMinutes: Int and overrides describe() to also include the runtime</li><li>An interface Playable with a method play() that prints &quot;Playing &lt;title&gt;...&quot;</li><li>Only Movie should implement Playable (you can’t “play” a book)</li><li>A function fun playAll(items: List&lt;Playable&gt;) that loops through and plays each one</li></ol><p>Starter skeleton:</p><pre>open class MediaItem(val title: String) {<br>    open fun describe() {<br>        println(&quot;\&quot;$title\&quot;&quot;)<br>    }<br>}</pre><pre>class Book(title: String, val author: String) : MediaItem(title) {<br>    // Your override here<br>}</pre><pre>interface Playable {<br>    fun play()<br>}</pre><pre>class Movie(title: String, val runtimeMinutes: Int) : MediaItem(title), Playable {<br>    // Override describe() to include runtime<br>    // Implement play()<br>}</pre><pre>fun playAll(items: List&lt;Playable&gt;) {<br>    // Your code: call play() on each<br>}</pre><pre>fun main() {<br>    val library: List&lt;MediaItem&gt; = listOf(<br>        Book(&quot;Atomic Habits&quot;, &quot;James Clear&quot;),<br>        Movie(&quot;Inception&quot;, 148),<br>        Book(&quot;Sapiens&quot;, &quot;Yuval Noah Harari&quot;),<br>        Movie(&quot;Arrival&quot;, 116)<br>    )</pre><pre>    println(&quot;--- Library ---&quot;)<br>    library.forEach { it.describe() }</pre><pre>    println(&quot;\n--- Playing movies ---&quot;)<br>    val playable = library.filterIsInstance&lt;Playable&gt;()<br>    playAll(playable)<br>}</pre><p>A small new piece of syntax to know: <strong>filterIsInstance&lt;Playable&gt;()</strong> is a collection operation that keeps only items of a specific type. Here it picks out the movies from a mixed list. We didn’t formally cover it on Day 15 — drop it in your back pocket.</p><p><strong>Bonus challenges:</strong></p><ul><li>Add a Podcast class — also implements Playable, but inherits from MediaItem directly. Test that it works with playAll.</li><li>Add a second interface Downloadable with download(). Have Movie implement both Playable and Downloadable. Notice how natural multiple interfaces feel.</li><li>Add an Audiobook class that’s both a Book (inheritance) AND Playable (interface). One thing being multiple roles is exactly what interfaces are for.</li><li><strong>Stretch:</strong> Use is type checks to write a function summarize(item: MediaItem) that prints different details based on the actual type. Then try to express the same logic with method overriding instead — and notice why the overriding version is cleaner.</li></ul><h3>🎓 Practice Beyond This Article</h3><p>The <a href="https://play.kotlinlang.org/koans/overview"><strong>Kotlin Koans — Properties</strong></a> section and the various interface-related tasks are excellent reps. If today felt heavy, working through a few of those is the fastest way to make it click.</p><h3>👉 Tomorrow: Day 21</h3><p>Today’s article showed you the manual way of building classes. Tomorrow we meet <strong>data classes</strong> — Kotlin’s superpower for classes whose main job is “hold some data.” With a single keyword, you get a clean toString, a working equals, free destructuring, a built-in copy method, and several other niceties. It’s one of those features that, once you’ve used it, you’ll wonder how other languages live without it.</p><p><strong>See you tomorrow.</strong></p><h3>📚 Series Navigation</h3><p><strong>Previous:</strong> Day 19 — Properties Deeper <em>(link)</em> <strong>You are here:</strong> Day 20 — Inheritance &amp; Interfaces <strong>Next:</strong> Day 21 — Data Classes <em>(link coming tomorrow)</em></p><p>If this article helped, a clap or share means the world. It tells Medium to surface this series to more learners.</p><h3>📊 References &amp; Further Reading</h3><ul><li><a href="https://kotlinlang.org/docs/inheritance.html">Official Kotlin docs — Inheritance</a></li><li><a href="https://kotlinlang.org/docs/interfaces.html">Kotlin docs — Interfaces</a></li><li><a href="https://kotlinlang.org/docs/inheritance.html#overriding-methods">Kotlin docs — Open and override</a></li><li><a href="https://play.kotlinlang.org/koans/overview">Kotlin Koans (free beginner exercises)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a9a42d6ec6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 19: Properties Deeper — Computed Values, Custom Getters & init Blocks]]></title>
            <link>https://kirupakaran094.medium.com/day-19-properties-deeper-computed-values-custom-getters-init-blocks-234175a3af4a?source=rss-f2f70e824880------2</link>
            <guid isPermaLink="false">https://medium.com/p/234175a3af4a</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Kirubakaran]]></dc:creator>
            <pubDate>Sun, 31 May 2026 01:56:00 GMT</pubDate>
            <atom:updated>2026-05-31T01:56:00.560Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*voUbLoRbArikgTvsUXFS-w.png" /></figure><h4>Android with Kotlin for Absolute Beginners — Day 19 of the Series</h4><h3>What Yesterday Left Unsaid</h3><p>Yesterday you wrote your first class. Student had a name and a score, both <strong>stored</strong> directly when the object was created. That’s the simplest kind of property — a value you set once and read back.</p><p>But properties in Kotlin can do more than just store values. They can be <strong>calculated</strong> every time you read them. They can have logic running when you write to them. They can validate themselves at the moment they’re created.</p><p>These features sound small. In practice, they’re how real Kotlin classes stay clean. Instead of writing student.score * 100 / maxScore everywhere in your code, you write student.percentage — and the class computes it for you, every time. Instead of trusting that someone constructs a Student with sensible values, the class refuses to be built with invalid ones.</p><p>This is a smaller article than yesterday — more polish than new shape. But the patterns matter. You’ll use them constantly once you’re writing real Android code.</p><blockquote>In real Android codebases, well-designed classes barely have any “loose code” calculating things on the side. The class itself answers every question you might ask of it. Today’s article is about how to get there.</blockquote><h3>What You’ll Learn Today</h3><ul><li>✅ Computed properties (no storage, calculated on demand)</li><li>✅ Custom getters</li><li>✅ Properties declared inside the class body</li><li>✅ The init block — running setup code when an object is born</li><li>✅ A quick word on secondary constructors (and why you’ll rarely need them)</li></ul><h3>A Quick Recap: Two Ways to Declare a Property</h3><p>So far, you’ve seen properties declared in <strong>the primary constructor</strong> — the parentheses after the class name:</p><pre>class Student(val name: String, val score: Int)</pre><p>There’s also a second way: declaring properties <strong>inside the class body</strong>, with val or var, just like a regular variable.</p><pre>class Student(val name: String, val score: Int) {<br>    val maxScore: Int = 100<br>}</pre><p>Now every Student has <em>three</em> properties: name, score, and maxScore. The first two come from the constructor; maxScore is a class-body property with a fixed default.</p><p>You can use both styles in the same class. The general rule:</p><ul><li><strong>Primary constructor</strong> — for properties whose value must be supplied when the object is built</li><li><strong>Class body</strong> — for properties that have a default, are calculated, or aren’t part of “what makes this object what it is”</li></ul><p>That’s it. There’s no big mystery — just two places to put properties.</p><h3>Computed Properties — The Magic Trick</h3><p>Here’s the feature that changes how you write classes.</p><p>A <strong>computed property</strong> doesn’t store a value. It calculates one each time you read it. Watch:</p><pre>class Student(val name: String, val score: Int) {<br>    val percentage: Int<br>        get() = (score * 100) / 100  // for now, max is hardcoded as 100<br>}</pre><pre>fun main() {<br>    val anuki = Student(name = &quot;Anuki&quot;, score = 87)<br>    println(anuki.percentage)   // 87<br>}</pre><p>Open the <a href="https://play.kotlinlang.org/">Kotlin Playground</a> and run it.</p><p>A few things to notice:</p><ul><li>val percentage: Int declares a property of type Int</li><li>It has <strong>no initial value</strong> — no = followed by a number</li><li>Instead, there’s a <strong>get()</strong> block right under it. That block runs every time someone reads student.percentage</li><li>The get() = ... form is a single-expression getter, same idea as Day 12’s single-expression functions</li></ul><p>To make the example more useful, let’s introduce a real maxScore:</p><pre>class Student(val name: String, val score: Int, val maxScore: Int = 100) {<br>    val percentage: Int<br>        get() = (score * 100) / maxScore</pre><pre>    val passes: Boolean<br>        get() = percentage &gt;= 50</pre><pre>    val grade: String<br>        get() = when {<br>            percentage &gt;= 90 -&gt; &quot;A&quot;<br>            percentage &gt;= 70 -&gt; &quot;B&quot;<br>            percentage &gt;= 50 -&gt; &quot;C&quot;<br>            else             -&gt; &quot;F&quot;<br>        }<br>}</pre><pre>fun main() {<br>    val anuki = Student(name = &quot;Anuki&quot;, score = 76, maxScore = 80)</pre><pre>    println(&quot;${anuki.name} scored ${anuki.score}/${anuki.maxScore}&quot;)<br>    println(&quot;Percentage: ${anuki.percentage}%&quot;)<br>    println(&quot;Passes: ${anuki.passes}&quot;)<br>    println(&quot;Grade: ${anuki.grade}&quot;)<br>}</pre><p>Run it. You should see:</p><pre>Anuki scored 76/80<br>Percentage: 95%<br>Passes: true<br>Grade: A</pre><p>Look at what just happened. percentage, passes, and grade look like normal properties — anuki.percentage, no parentheses, no method call syntax. But underneath, each one runs a calculation every time it’s accessed.</p><p><strong>This is the heart of well-designed classes.</strong> The object answers questions about itself, in its own language, computed from its own data. The code calling it doesn’t need to remember the formula.</p><blockquote>In real Android development, computed properties are everywhere. A User object might have a stored birthDate but a computed age. A ShoppingCart might have stored items but a computed total. A Message might have a stored timestamp but a computed displayTime like “5 minutes ago.” Every one of those is a one-line getter that hides the calculation from everyone using the class.</blockquote><h3>Computed vs Stored: Which to Use?</h3><p>A property can either be <strong>stored</strong> (you keep the value in memory) or <strong>computed</strong> (you calculate it every time). How do you decide?</p><p>Quick heuristic:</p><p>Use <strong>stored</strong> when…</p><p>Use <strong>computed</strong> when…</p><p>The value is supplied from outside</p><p>The value depends entirely on other properties</p><p>Calculating it is expensive</p><p>The calculation is cheap</p><p>The value doesn’t change often</p><p>The value should always reflect the latest state</p><p>For Student:</p><ul><li>name and score are <strong>stored</strong> — they come from outside</li><li>percentage, grade, and passes are <strong>computed</strong> — they’re entirely derived from score and maxScore</li></ul><p>The benefit of computed: <strong>the values are always correct.</strong> If you stored percentage and then score changed, the stored percentage would be wrong. With a computed property, that bug is impossible — it’s recalculated every time you read it.</p><h3>Custom Setters (Briefly)</h3><p>Properties can also have custom <strong>setters</strong> — code that runs when you write to a var. It’s less common than custom getters, but worth knowing it exists:</p><pre>class Thermometer {<br>    var temperature: Double = 0.0<br>        set(value) {<br>            require(value in -100.0..200.0) { &quot;Temperature out of range&quot; }<br>            field = value<br>        }<br>}</pre><pre>fun main() {<br>    val t = Thermometer()<br>    t.temperature = 22.5     // OK<br>    println(t.temperature)   // 22.5</pre><pre>    t.temperature = 500.0    // 💥 Crashes with the require message<br>}</pre><p>A couple of notes:</p><ul><li>set(value) is the setter block; value is the new value being assigned</li><li>field is a special keyword — it refers to the underlying storage of this property. Use it to actually save the value</li><li>require(...) is the same defensive-coding function from Day 18 — throws if its condition is false</li></ul><p>You won’t write custom setters often. But you’ll see them in real codebases (especially for properties that need to fire side effects, like UI updates on Android), so being able to read them matters.</p><h3>The init Block in Depth</h3><p>Yesterday you saw a one-liner version of init. Let’s properly explain it.</p><p>The init block runs <strong>once</strong>, immediately after the primary constructor has set up its properties. It’s the right place for setup code that depends on the constructor values.</p><pre>class Student(val name: String, val score: Int) {<br>    init {<br>        println(&quot;Creating student: $name with score $score&quot;)<br>        require(score in 0..100) { &quot;Score must be 0-100&quot; }<br>        require(name.isNotBlank()) { &quot;Name cannot be blank&quot; }<br>    }<br>}</pre><pre>fun main() {<br>    val anuki = Student(&quot;Anuki&quot;, 95)   // prints the creating message<br>    val bad = Student(&quot;&quot;, 50)          // 💥 crashes on the require check<br>}</pre><p>Run that. You’ll see the print for the first line, then the crash on the second.</p><p>A class can have multiple init blocks — they run <strong>top to bottom</strong> in the order they appear:</p><pre>class Demo(val x: Int) {<br>    init { println(&quot;First init: x = $x&quot;) }<br>    val doubled = x * 2<br>    init { println(&quot;Second init: doubled = $doubled&quot;) }<br>}</pre><p>Init blocks run interleaved with body property initializers, in source order. You probably won’t need multiple init blocks early on, but the rule is: <strong>everything in the class body executes top-to-bottom when an object is created.</strong></p><h3>What init is good for</h3><ul><li><strong>Validation</strong> — refuse to construct invalid objects (the require pattern from above)</li><li><strong>Side effects on creation</strong> — logging, registering with another system, scheduling something</li><li><strong>Setup based on constructor values</strong> — initializing a property whose value depends on a calculation of the inputs</li></ul><p>What init is <em>not</em> good for: doing heavy work or asynchronous operations. Object construction should be cheap. If you find yourself wanting to fetch data from the internet in an init block, you’re in the wrong place — that work belongs elsewhere.</p><h3>Secondary Constructors (Briefly)</h3><p>You’ll occasionally see Kotlin code with extra constructors beyond the primary one:</p><pre>class Student(val name: String, val score: Int) {<br>    constructor(name: String) : this(name, 0)   // delegates to primary<br>}</pre><pre>fun main() {<br>    val newStudent = Student(&quot;Tharushi&quot;)   // score defaults to 0<br>    val full = Student(&quot;Anuki&quot;, 95)<br>}</pre><p>The constructor(name: String) : this(name, 0) is a <strong>secondary constructor</strong>. It takes its own parameters and then <em>delegates</em> to the primary constructor by calling this(...).</p><p>Here’s the honest truth: <strong>you’ll rarely write these in modern Kotlin.</strong> The same effect — letting callers skip parameters — is almost always handled more cleanly with <strong>default arguments</strong> (Day 13):</p><pre>// The modern Kotlin way — no secondary constructor needed<br>class Student(val name: String, val score: Int = 0)</pre><p>One line. Same outcome. Less ceremony.</p><p>Secondary constructors mostly show up in code that interoperates with Java (which doesn’t have default arguments) or in older codebases. Recognize them when reading code; reach for default arguments when writing your own.</p><h3>Putting It Together: A Cleaner Student Class</h3><p>Here’s everything from today applied to the Student class:</p><pre>class Student(<br>    val name: String,<br>    val score: Int,<br>    val maxScore: Int = 100<br>) {<br>    init {<br>        require(name.isNotBlank()) { &quot;Student name cannot be blank&quot; }<br>        require(score in 0..maxScore) { &quot;Score must be 0..$maxScore&quot; }<br>    }</pre><pre>    val percentage: Int<br>        get() = (score * 100) / maxScore</pre><pre>    val grade: String<br>        get() = when {<br>            percentage &gt;= 90 -&gt; &quot;A&quot;<br>            percentage &gt;= 70 -&gt; &quot;B&quot;<br>            percentage &gt;= 50 -&gt; &quot;C&quot;<br>            else             -&gt; &quot;F&quot;<br>        }</pre><pre>    val passes: Boolean<br>        get() = percentage &gt;= 50</pre><pre>    fun report(): String =<br>        &quot;$name: $score/$maxScore ($percentage%, grade $grade)&quot;<br>}</pre><pre>fun main() {<br>    val students = listOf(<br>        Student(&quot;Anuki&quot;, 95),<br>        Student(&quot;Kiruba&quot;, 88),<br>        Student(&quot;Sahan&quot;, 48),<br>        Student(&quot;Tharushi&quot;, 72, maxScore = 80)<br>    )</pre><pre>    students.forEach { println(it.report()) }<br>}</pre><p>Run it. You should see:</p><pre>Anuki: 95/100 (95%, grade A)<br>Kiruba: 88/100 (88%, grade B)<br>Sahan: 48/100 (48%, grade F)<br>Tharushi: 72/80 (90%, grade A)</pre><p>Look at how clean main is. <strong>All the logic lives in the class.</strong> The list of students says nothing about percentages or grades — the class knows. Compare this to Day 17, where every calculation lived loose in main. Today’s version is significantly more maintainable.</p><p>This is the payoff for everything in today’s article. Computed properties + validation + a small report() method = a class that’s actually pleasant to use.</p><h3>Common Mistakes Beginners Make</h3><h3>❌ Mistake 1: Trying to give a computed property an initial value</h3><pre>val percentage: Int = 0     // ❌ stored property<br>    get() = score * 100 / maxScore  // ❌ can&#39;t have both</pre><pre>val percentage: Int          // ✅ no initial value<br>    get() = score * 100 / maxScore</pre><p>A computed property has <em>no</em> initial value — only a getter.</p><h3>❌ Mistake 2: Using field outside a setter</h3><pre>class X {<br>    var x: Int = 0<br>        get() = field * 2   // ✅ field is allowed in getters too<br>}</pre><p>Actually that one <em>is</em> legal — but field only refers to the property’s own backing storage. You can’t use it as a general variable name. Treat it as a special keyword exclusive to property accessors.</p><h3>❌ Mistake 3: Doing expensive work in init or a getter</h3><pre>class User(val id: String) {<br>    val profile: Profile<br>        get() = fetchFromInternet(id)   // ❌ every access hits the network<br>}</pre><p>Computed properties run <em>every time</em>. If a calculation is expensive, store the result or load it lazily. (Kotlin has lazy { } for this — we’ll meet it later.)</p><h3>❌ Mistake 4: Letting init blocks do too much</h3><pre>class Game {<br>    init {<br>        loadFromDisk()<br>        connectToServer()<br>        startMusic()<br>    }<br>}</pre><p>Construction should be fast. If creating an object requires real work, expose that work as separate methods (init(), start(), etc.) the caller invokes deliberately.</p><h3>❌ Mistake 5: Forgetting that require throws</h3><pre>init {<br>    require(score in 0..100)<br>}<br>// If score is 150, this DOESN&#39;T just print a warning — it crashes the program.</pre><p>That’s actually the point. But know what you’re signing up for: require is for <em>invalid inputs we cannot proceed with</em>. For “soft” validation, use an if and handle the case differently.</p><h3>💪 Today’s Practice Challenge</h3><p>Build a <strong>BankAccount class</strong> that uses today’s concepts thoughtfully.</p><p>Requirements:</p><ol><li>The account is created with a holder (name) and an optional startingBalance (default 0.0)</li><li>The balance property is a var — it changes over time</li><li>There’s a computed property isOverdrawn: Boolean — true if balance is below zero</li><li>There’s a computed property status: String — &quot;Healthy&quot; if balance ≥ 1000, &quot;Low&quot; if balance is positive but below 1000, &quot;Overdrawn&quot; otherwise</li><li>init must validate that holder isn’t blank and startingBalance isn’t more negative than -1000 (no extreme starting debt allowed)</li><li>A method deposit(amount: Double) — adds to balance (only if amount &gt; 0)</li><li>A method withdraw(amount: Double) — subtracts from balance (don’t allow withdrawing more than balance + 1000)</li></ol><p>Starter skeleton:</p><pre>class BankAccount(<br>    val holder: String,<br>    startingBalance: Double = 0.0<br>) {<br>    init {<br>        // Your validation here<br>    }</pre><pre>    var balance: Double = startingBalance<br>        private set    // see below</pre><pre>    val isOverdrawn: Boolean<br>        get() = TODO(&quot;your code&quot;)</pre><pre>    val status: String<br>        get() = TODO(&quot;your code&quot;)</pre><pre>    fun deposit(amount: Double) {<br>        // Your code<br>    }</pre><pre>    fun withdraw(amount: Double) {<br>        // Your code<br>    }<br>}</pre><pre>fun main() {<br>    val acc = BankAccount(&quot;Kiruba&quot;, 500.0)<br>    println(&quot;Balance: ${acc.balance}, Status: ${acc.status}&quot;)</pre><pre>    acc.deposit(1000.0)<br>    println(&quot;After deposit: ${acc.balance}, Status: ${acc.status}&quot;)</pre><pre>    acc.withdraw(2000.0)<br>    println(&quot;After withdraw: ${acc.balance}, Status: ${acc.status}&quot;)<br>    println(&quot;Overdrawn? ${acc.isOverdrawn}&quot;)<br>}</pre><p>A small new piece of syntax to know: private set after the property means <em>the property can be read from outside, but only the class itself can modify it.</em> This prevents callers from doing acc.balance = 1000000 — they have to go through deposit and withdraw. We’ll cover visibility modifiers properly soon; for now, it’s enough to know what this does.</p><p><strong>Bonus challenges:</strong></p><ul><li>Add a computed property monthsAtLowBalance: Int — well, actually no, you don’t have months yet. Instead: add a transactionCount: Int that increments inside both deposit and withdraw</li><li>Add an init block that prints &quot;Account opened for $holder&quot; on creation</li><li>Make a list of three BankAccounts and use Day 15 collection operations: total balance across all accounts, the holder with the highest balance, accounts that are overdrawn</li><li><strong>Stretch:</strong> Add an interestRate property with a default of 0.05 (5%) and a method applyInterest() that increases the balance by that percentage. Make the rate a var so it can be adjusted later.</li></ul><h3>🎓 Practice Beyond This Article</h3><p>The <a href="https://play.kotlinlang.org/koans/overview"><strong>Kotlin Koans — Classes</strong></a> section continues to be great practice. Many tasks at this level explicitly exercise getters, validation, and computed properties.</p><h3>👉 Tomorrow: Day 20</h3><p>You’ve been building isolated classes — each Student, Book, or BankAccount standing on its own. Tomorrow we connect them. We’ll learn <strong>inheritance</strong> — how to build new classes from existing ones — and <strong>interfaces</strong> — how to define capabilities that multiple unrelated classes can share. Together they’re the most powerful pattern in object-oriented design, and Kotlin’s syntax for both is clean and approachable.</p><p><strong>See you tomorrow.</strong></p><h3>📚 Series Navigation</h3><p><strong>Previous:</strong> Day 18 — Classes in Kotlin <em>(link)</em> <strong>You are here:</strong> Day 19 — Properties Deeper: Computed Values &amp; init Blocks <strong>Next:</strong> Day 20 — Inheritance &amp; Interfaces <em>(link coming tomorrow)</em></p><p>If this article helped, a clap or share means the world. It tells Medium to surface this series to more learners.</p><h3>📊 References &amp; Further Reading</h3><ul><li><a href="https://kotlinlang.org/docs/properties.html">Official Kotlin docs — Properties</a></li><li><a href="https://kotlinlang.org/docs/properties.html#getters-and-setters">Kotlin docs — Getters and setters</a></li><li><a href="https://kotlinlang.org/docs/classes.html#initializer-blocks">Kotlin docs — Classes: init blocks</a></li><li><a href="https://kotlinlang.org/docs/classes.html#secondary-constructors">Kotlin docs — Secondary constructors</a></li><li><a href="https://play.kotlinlang.org/koans/overview">Kotlin Koans (free beginner exercises)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=234175a3af4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 18: Classes — Where You Start Modeling Your Own World]]></title>
            <link>https://kirupakaran094.medium.com/day-18-classes-where-you-start-modeling-your-own-world-dd0c95c47cd2?source=rss-f2f70e824880------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd0c95c47cd2</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Kirubakaran]]></dc:creator>
            <pubDate>Sat, 30 May 2026 01:46:00 GMT</pubDate>
            <atom:updated>2026-05-30T01:46:00.639Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*imhkett0kMLCjkypBEDs-w.png" /></figure><h4>Android with Kotlin for Absolute Beginners — Day 18 of the Series</h4><h3>The Moment Yesterday’s Code Started to Feel Awkward</h3><p>Look back at yesterday’s Grade Analyzer. Every student was a Pair&lt;String, Int&gt; — name on the left, score on the right. The code worked. But somewhere around the fifth time you typed it.second to mean “score,” something probably felt off.</p><p>.second doesn’t mean <em>score</em>. It means “the second item in this pair.” Your code knows the value is a score, but the code doesn’t <em>say</em> so. A reader six months later would have to read the surrounding context to figure out what .first and .second are.</p><p>That mismatch — between what your data <strong>is</strong> and what your code <strong>calls</strong> it — is what classes solve.</p><p>A class lets you create your <strong>own types</strong>. Instead of cramming a student into a generic Pair&lt;String, Int&gt;, you can define a Student type with proper named properties — name and score — that mean exactly what they say. The result is code that reads almost like English and is dramatically harder to misuse.</p><p>Welcome to <strong>object-oriented programming</strong>. Classes are the foundation of the second half of Phase 1, and they unlock most of Phase 2 and 3. Don’t rush this article. Type every example. Re-read sections that feel fuzzy.</p><blockquote>This is the article where Kotlin starts to feel less like a scripting language and more like a real engineering tool. Coming from Flutter, I had Dart’s class syntax in my head — and Kotlin’s was almost the same but cleaner. If you’re learning Kotlin as your first typed-class language, even better: you’ll skip a lot of legacy verbosity that older languages still carry.</blockquote><h3>What You’ll Learn Today</h3><ul><li>✅ What a class is and what it isn’t</li><li>✅ Defining a class with properties</li><li>✅ Creating objects (instances) from a class</li><li>✅ Adding behavior with member functions (methods)</li><li>✅ val vs var properties</li><li>✅ Refactoring yesterday’s project to use a real class</li></ul><h3>What Is a Class, Really?</h3><p>A class is a <strong>blueprint</strong> for creating things.</p><p>That’s the analogy every programming book uses, and it’s actually a good one. A blueprint for a house describes what every house of that type <em>will have</em> — number of rooms, layout, plumbing — but the blueprint itself isn’t a house. Each house built from the blueprint is an <strong>instance</strong>, a real thing made from the description.</p><p>In Kotlin:</p><ul><li>The <strong>class</strong> is the blueprint (class Student { ... })</li><li>An <strong>object</strong> (or instance) is a real thing built from it (Student(name = &quot;Anuki&quot;, score = 95))</li><li>You can build as many objects from one class as you need — each is independent</li></ul><p>Some classes you’ve already used:</p><ul><li>String is a class. &quot;hello&quot; is an instance.</li><li>Int is a class. 42 is an instance.</li><li>List&lt;String&gt; is a class. listOf(&quot;a&quot;, &quot;b&quot;) is an instance.</li></ul><p>Today you’ll define your own. Open the <a href="https://play.kotlinlang.org/">Kotlin Playground</a> and let’s start.</p><h3>Your First Class</h3><p>Here’s the minimum:</p><pre>class Student(val name: String, val score: Int)</pre><pre>fun main() {<br>    val anuki = Student(name = &quot;Anuki&quot;, score = 95)<br>    val kiruba = Student(name = &quot;Kiruba&quot;, score = 88)</pre><pre>    println(anuki.name)     // Anuki<br>    println(anuki.score)    // 95<br>    println(kiruba.name)    // Kiruba<br>}</pre><p>Run it. You should see three lines of output.</p><p>Let’s break down the class definition:</p><pre>class Student(val name: String, val score: Int)</pre><p>Piece</p><p>What it means</p><p>class</p><p>“I’m defining a new type.”</p><p>Student</p><p>The name of the type. By convention, type names start with <strong>a capital letter</strong>.</p><p>(val name: String, val score: Int)</p><p>The <strong>primary constructor</strong>. Says: “Every Student is built with a name and a score.”</p><p>val name, val score</p><p>These are also <strong>properties</strong> — they’re stored on each instance and accessible from outside via .name and .score.</p><p>That whole thing fits on one line because Kotlin removed all the ceremony older languages require. Compare to Java, which would need maybe 15 lines for the same effect.</p><h3>Creating an instance</h3><pre>val anuki = Student(name = &quot;Anuki&quot;, score = 95)</pre><p>To create a Student, you call its name like a function and pass the constructor arguments. No new keyword (Kotlin dropped it — Student(...) is enough).</p><p>Notice I used <strong>named arguments</strong> (Day 13!) — name = &quot;Anuki&quot;, score = 95. You don’t have to. Student(&quot;Anuki&quot;, 95) works too. But named arguments are especially nice for classes because the parameter names line up with the property names, making the call read like a sentence: <em>“create a Student with name ‘Anuki’ and score 95.”</em></p><h3>Accessing properties</h3><pre>println(anuki.name)     // &quot;Anuki&quot;<br>println(anuki.score)    // 95</pre><p>Dot notation. Same syntax as students.size or &quot;hello&quot;.uppercase(). Once an object exists, you reach inside via .propertyName.</p><h3>val vs var Properties</h3><p>Notice we used val for name and score:</p><pre>class Student(val name: String, val score: Int)</pre><p>That means once a Student is created, you can’t change their name or score:</p><pre>val anuki = Student(name = &quot;Anuki&quot;, score = 95)<br>anuki.score = 100    // ❌ Error — score is val</pre><p>If you <em>want</em> a property to be changeable, use var:</p><pre>class Student(val name: String, var score: Int)</pre><pre>fun main() {<br>    val anuki = Student(name = &quot;Anuki&quot;, score = 95)<br>    anuki.score = 100    // ✅ score is var, so this works<br>    println(anuki.score) // 100<br>}</pre><p>The same Day 3 rule applies: <strong>prefer </strong><strong>val by default</strong>, only reach for var when the property genuinely needs to change.</p><p>For our Student example, the score might change as new tests come in — so var is a reasonable choice. The name probably won’t — so val stays.</p><blockquote>One subtle but important thing: making a property val doesn’t mean the <strong>list of students</strong> can’t change. It means <strong>each individual student’s score</strong> can’t change. The two are different freezes at different levels. We’ll come back to this distinction in real code soon.</blockquote><h3>Adding Behavior: Member Functions (Methods)</h3><p>Properties hold data. <strong>Methods</strong> (also called member functions) hold <em>behavior</em> — things the object can do.</p><p>Let’s give Student a method:</p><pre>class Student(val name: String, val score: Int) {<br>    fun passes(threshold: Int): Boolean {<br>        return score &gt;= threshold<br>    }<br>}</pre><pre>fun main() {<br>    val anuki = Student(name = &quot;Anuki&quot;, score = 95)<br>    val sahan = Student(name = &quot;Sahan&quot;, score = 48)</pre><pre>    println(anuki.passes(50))    // true<br>    println(sahan.passes(50))    // false<br>}</pre><p>A few things to notice:</p><ol><li>Methods go <strong>inside the class body</strong> (the { } after the constructor)</li><li>They’re just functions — same syntax as Day 12. The only difference is they’re defined <em>inside</em> a class, so they have access to all the properties of the class without having to pass them in</li><li>Inside passes, we wrote score — meaning <em>this student’s</em> score. We didn’t have to write student.score or this.score. Inside a class, properties are directly available.</li><li>You call methods with the same dot syntax: anuki.passes(50)</li></ol><p>Methods can be single-expression functions too, just like regular ones:</p><pre>class Student(val name: String, val score: Int) {<br>    fun passes(threshold: Int): Boolean = score &gt;= threshold<br>    fun grade(): String = when {<br>        score &gt;= 90 -&gt; &quot;A&quot;<br>        score &gt;= 70 -&gt; &quot;B&quot;<br>        score &gt;= 50 -&gt; &quot;C&quot;<br>        else        -&gt; &quot;F&quot;<br>    }<br>}</pre><p>Now Student knows three things about itself: its name, its score, and how to compute its grade. The grading logic from yesterday’s project — which lived loosely in main — now lives <em>with the data it operates on</em>. That’s the core idea of object-oriented programming in one sentence:</p><blockquote><em>Put data and the behaviour that acts on that data together, in one place.</em></blockquote><h3>Refactoring Yesterday’s Project</h3><p>Let’s see how much cleaner yesterday’s Grade Analyzer becomes with a proper Student class. Just the relevant changes — focus on what improved:</p><p><strong>Before (Day 17):</strong></p><pre>val students = listOf(<br>    &quot;Kiruba&quot; to 88,<br>    &quot;Anuki&quot;  to 95,<br>    &quot;Sahan&quot;  to 48<br>)</pre><pre>val passedCount = students.count { it.second &gt;= passingMark }<br>val grades = students.map { gradeFor(it.second) }</pre><p><strong>After (using a class):</strong></p><pre>class Student(val name: String, val score: Int) {<br>    fun passes(threshold: Int) = score &gt;= threshold<br>    fun grade(): String = when {<br>        score &gt;= 90 -&gt; &quot;A&quot;<br>        score &gt;= 70 -&gt; &quot;B&quot;<br>        score &gt;= 50 -&gt; &quot;C&quot;<br>        else        -&gt; &quot;F&quot;<br>    }<br>}</pre><pre>val students = listOf(<br>    Student(&quot;Kiruba&quot;, 88),<br>    Student(&quot;Anuki&quot;, 95),<br>    Student(&quot;Sahan&quot;, 48)<br>)</pre><pre>val passedCount = students.count { it.passes(passingMark) }<br>val grades = students.map { it.grade() }</pre><p>Look at the lambdas now. <strong>it.passes(passingMark)</strong> says exactly what it means — no need to remember that .second is the score. <strong>it.grade()</strong> does the grading inside the object itself, not via an external helper function.</p><p>The code reads almost like English: <em>“count the students who pass the threshold; map each student to their grade.”</em></p><p>This shift — from “operate on tuples by position” to “ask objects about themselves” — is one of the biggest productivity wins in object-oriented design. Once you start writing classes, you’ll catch yourself reaching for them anywhere you find yourself remembering “wait, what was .first again?”</p><h3>Multiple Constructors? (Briefly)</h3><p>You’ll see this pattern in some Kotlin tutorials and want to know what it is. A class can have a init block — code that runs when an instance is created:</p><pre>class Student(val name: String, val score: Int) {<br>    init {<br>        require(score in 0..100) { &quot;Score must be 0-100, got $score&quot; }<br>    }<br>}</pre><p>Now creating a student with an invalid score crashes immediately with a clear message:</p><pre>val bad = Student(&quot;Test&quot;, 150)<br>// 💥 IllegalArgumentException: Score must be 0-100, got 150</pre><p>This is <strong>defensive coding</strong> — catching bad data right at the source, before it propagates through your program. require is a built-in Kotlin function that throws an error if its condition is false. We’ll see more of this pattern later.</p><p>You can have <em>additional</em> constructors beyond the primary one too, but you almost never need them in modern Kotlin code. For now, the one primary constructor in the parentheses after the class name is all you’ll write.</p><h3>Common Mistakes Beginners Make</h3><h3>❌ Mistake 1: Forgetting val or var in the primary constructor</h3><pre>class Student(name: String, score: Int)     // ❌ name and score are just parameters<br>// You can use them inside init { ... } but they&#39;re NOT properties.</pre><pre>class Student(val name: String, val score: Int)  // ✅ now they&#39;re properties</pre><p>Without val/var, those are just constructor parameters — used only during creation, not stored on the instance. You can’t access student.name later.</p><h3>❌ Mistake 2: Forgetting that classes need the class keyword</h3><pre>Student(val name: String)            // ❌ Just floating in the air<br>class Student(val name: String)      // ✅</pre><h3>❌ Mistake 3: Calling a class like a function without the class definition</h3><pre>val s = Student(&quot;a&quot;, 50)             // ❌ Error if Student isn&#39;t defined yet</pre><p>Define the class before using it (or above your main). Kotlin can sometimes hoist definitions, but the safe habit is: declare first, use later.</p><h3>❌ Mistake 4: Mutating properties marked val</h3><pre>class Student(val name: String, val score: Int)<br>val s = Student(&quot;a&quot;, 50)<br>s.score = 60                         // ❌ score is val</pre><p>Make it var if it genuinely needs to change. If most students’ scores don’t change but a few do, var is the right call — val should mean “this won’t change for <em>any</em> student.”</p><h3>❌ Mistake 5: Trying to print a class instance directly</h3><pre>val s = Student(&quot;Anuki&quot;, 95)<br>println(s)<br>// Prints something like: Student@5e91993f</pre><p>That weird @5e91993f is a memory address. Useless. We’ll fix this beautifully on Day 21 when we cover <strong>data classes</strong> — they automatically format printouts nicely. For now, just print the individual properties: println(&quot;${s.name}: ${s.score}&quot;).</p><h3>💪 Today’s Practice Challenge</h3><p>Build a small <strong>Book class</strong> with some real behavior.</p><pre>class Book(<br>    val title: String,<br>    val author: String,<br>    val pages: Int,<br>    var currentPage: Int = 0<br>) {<br>    fun progressPercent(): Int {<br>        // Your code: return percentage read (currentPage out of pages)<br>        return 0<br>    }</pre><pre>    fun isFinished(): Boolean {<br>        // Your code: true if currentPage &gt;= pages<br>        return false<br>    }</pre><pre>    fun read(pagesRead: Int) {<br>        // Your code: advance currentPage by pagesRead<br>        //            (but don&#39;t exceed total pages — use minOf)<br>    }<br>}</pre><pre>fun main() {<br>    val book = Book(<br>        title = &quot;Atomic Habits&quot;,<br>        author = &quot;James Clear&quot;,<br>        pages = 320<br>    )</pre><pre>    book.read(50)<br>    println(&quot;${book.title}: ${book.progressPercent()}% read&quot;)<br>    println(&quot;Finished? ${book.isFinished()}&quot;)</pre><pre>    book.read(300)<br>    println(&quot;After more reading: ${book.progressPercent()}% read&quot;)<br>    println(&quot;Finished? ${book.isFinished()}&quot;)<br>}</pre><p>Fill in the three methods. The output should look like:</p><pre>Atomic Habits: 15% read<br>Finished? false<br>After more reading: 100% read<br>Finished? true</pre><p><strong>Bonus challenges:</strong></p><ul><li>Add a daysRemaining(pagesPerDay: Int): Int method that estimates how many days you have left at a given reading pace</li><li>Add an init block that throws if pages &lt;= 0 (a book with zero pages doesn’t make sense)</li><li>Make a list of three Book objects and use <strong>Day 15 collection operations</strong> on them: total pages across all books, the longest book, books that are more than 50% read</li><li><strong>Stretch:</strong> Add a String property genre with a default value of &quot;Unknown&quot;, and write booksByGenre(books: List&lt;Book&gt;): Map&lt;String, List&lt;Book&gt;&gt; using groupBy { it.genre } from the docs</li></ul><h3>🎓 Practice Beyond This Article</h3><p>The <a href="https://play.kotlinlang.org/koans/overview"><strong>Kotlin Koans — Classes</strong></a> section is exactly today’s material in exercise form. Highly recommended if today felt heavy — repetition is what makes classes feel natural.</p><h3>👉 Tomorrow: Day 19</h3><p>You learned the basics today. Tomorrow we go deeper into what classes can do: <strong>properties with custom getters, computed properties, the </strong><strong>init block in depth, and the difference between primary and secondary constructors.</strong> It builds on today directly — you’ll be glad you typed out the examples.</p><p><strong>See you tomorrow.</strong></p><h3>📚 Series Navigation</h3><p><strong>Previous:</strong> Day 17 — Mini Project #3: Student Grade Analyzer <em>(link)</em> <strong>You are here:</strong> Day 18 — Classes in Kotlin <strong>Next:</strong> Day 19 — Properties, Methods &amp; Constructors <em>(link coming tomorrow)</em></p><p>If this article helped, a clap or share means the world. It tells Medium to surface this series to more learners.</p><h3>📊 References &amp; Further Reading</h3><ul><li><a href="https://kotlinlang.org/docs/classes.html">Official Kotlin docs — Classes</a></li><li><a href="https://kotlinlang.org/docs/properties.html">Kotlin docs — Properties</a></li><li><a href="https://kotlinlang.org/docs/visibility-modifiers.html">Kotlin docs — Visibility modifiers (preview)</a></li><li><a href="https://play.kotlinlang.org/koans/overview">Kotlin Koans (free beginner exercises)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd0c95c47cd2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 17: Mini Project #3 — A Student Grade Analyzer]]></title>
            <link>https://kirupakaran094.medium.com/day-17-mini-project-3-a-student-grade-analyzer-0dedce0d8d5d?source=rss-f2f70e824880------2</link>
            <guid isPermaLink="false">https://medium.com/p/0dedce0d8d5d</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Kirubakaran]]></dc:creator>
            <pubDate>Fri, 29 May 2026 02:01:00 GMT</pubDate>
            <atom:updated>2026-05-29T02:01:00.944Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZZ1Wk2BSx3NFkr063LKbLA.png" /></figure><h4>Android with Kotlin for Absolute Beginners — Day 17 of the Series</h4><h3>Seventeen Days In. Time to Build Something That Feels Real.</h3><p>Look back at where you were on Day 7. You’d just built a simple personal greeting program. Variables, types, if/else, string templates. It was a real win.</p><p>Now look at what you’ve added since: null safety, when, loops, two flavors of mini project, functions, default and named arguments, three kinds of collections, thirteen collection operations, and lambdas.</p><p>That’s a lot. Today we put it to work.</p><p>We’re going to build a <strong>Student Grade Analyzer</strong> — a small program that takes a class of students with their test scores and produces a report: class average, top scorer, pass rate, grade distribution, and a few other useful numbers. The kind of utility a real teacher might genuinely use, just without the user interface.</p><p>It’s also the project I’d use to spot whether a Phase 1 student is actually retaining the material. Every concept from the past week shows up. If you can finish it, you’re ready for the rest of Phase 1.</p><blockquote>I noticed something while writing this article: the techniques you’ll use here are nearly identical to what an Android dev uses to compute “this user’s average response time” or “the top 5 most-played songs” or “messages per day.” The shape of real-world data processing is the same shape as a grade analyzer. You’re not doing toy work today — you’re practicing the actual moves.</blockquote><h3>What You’ll Use Today (Recap)</h3><ul><li><strong>Day 12</strong> — Functions to organize code</li><li><strong>Day 13</strong> — Default and named arguments</li><li><strong>Day 14</strong> — Lists and Maps</li><li><strong>Day 15</strong> — filter, map, sumOf, count, maxByOrNull, sortedByDescending, average</li><li><strong>Day 16</strong> — Lambdas to power those operations</li><li><strong>Day 9</strong> — when for grade categories</li><li><strong>Day 8</strong> — Null safety patterns for empty-list edge cases</li></ul><p>If anything below feels fuzzy, go back to the article — that’s what they’re there for.</p><h3>The Project: What We’re Building</h3><p>Here’s the output we’re aiming for:</p><pre>============= CLASS PERFORMANCE REPORT =============<br>Class: Kotlin Foundations - Section A<br>Students enrolled: 8</pre><pre>------------------- SUMMARY ------------------------<br>Class average:     72.4<br>Highest score:     95 (Anuki)<br>Lowest score:      48 (Sahan)<br>Passed (&gt;= 50):    7 of 8<br>Pass rate:         88%</pre><pre>----------------- GRADE BREAKDOWN ------------------<br>A (90+):   1 student<br>B (70-89): 4 students<br>C (50-69): 2 students<br>F (&lt; 50):  1 student</pre><pre>----------------- TOP 3 STUDENTS -------------------<br>1. Anuki      —  95<br>2. Kiruba     —  88<br>3. Tharushi   —  84</pre><p>Real-looking. Useful. About 60 lines of Kotlin. Let’s build it in five steps.</p><h3>Step 1: Set Up the Data</h3><p>Open the <a href="https://play.kotlinlang.org/">Kotlin Playground</a> and start fresh. We need a way to hold a student and their score together. Yesterday’s to syntax handles this elegantly:</p><pre>fun main() {<br>    val className = &quot;Kotlin Foundations - Section A&quot;<br>    val passingMark = 50</pre><pre>    val students = listOf(<br>        &quot;Kiruba&quot;   to 88,<br>        &quot;Anuki&quot;    to 95,<br>        &quot;Sahan&quot;    to 48,<br>        &quot;Tharushi&quot; to 84,<br>        &quot;Pasindu&quot;  to 72,<br>        &quot;Nimal&quot;    to 61,<br>        &quot;Lakshmi&quot;  to 79,<br>        &quot;Ravi&quot;     to 52<br>    )<br>}</pre><p>A few choices worth flagging:</p><ul><li>Each student is a <strong>Pair&lt;String, Int&gt;</strong> — Kotlin’s tiny built-in type for two values. The to keyword creates them. You met to in mapOf(...) on Day 14; it works outside maps too.</li><li>For each pair, you can access the name via .first and the score via .second. That’ll matter in a moment.</li><li>passingMark = 50 is a val because it doesn’t change. The threshold for passing is fixed.</li></ul><blockquote>In a real Android app, this list would come from a database or API. For now we hard-code it — same pattern as Day 11. The point isn’t where the data comes from, but what you do with it once you have it.</blockquote><h3>Step 2: Print the Header</h3><p>Easy bit first — get the top of the report on screen:</p><pre>println(&quot;============= CLASS PERFORMANCE REPORT =============&quot;)<br>    println(&quot;Class: $className&quot;)<br>    println(&quot;Students enrolled: ${students.size}&quot;)<br>    println()</pre><p>students.size is built into every list — it tells you how many items are in it. You used it on Day 14.</p><p>Run what you have so far. The header should print cleanly. We’ll build the rest in pieces.</p><h3>Step 3: Calculate the Summary Stats</h3><p>Here’s where Day 15’s operations earn their keep. <strong>Each of these is one line.</strong> Try writing them yourself before reading the answer:</p><pre>val average = students.map { it.second }.average()<br>    val highest = students.maxByOrNull { it.second }<br>    val lowest = students.minByOrNull { it.second }<br>    val passedCount = students.count { it.second &gt;= passingMark }<br>    val passRate = (passedCount * 100) / students.size</pre><p>Let’s read each one carefully — the patterns are worth burning in:</p><ul><li><strong>students.map { it.second }.average()</strong> — pull out just the scores into a new list, then call average(). Two operations chained.</li><li><strong>students.maxByOrNull { it.second }</strong> — find the pair whose .second (the score) is the largest. Returns a Pair&lt;String, Int&gt;? (nullable, in case the list is empty).</li><li><strong>students.minByOrNull { it.second }</strong> — same idea, but smallest.</li><li><strong>students.count { it.second &gt;= passingMark }</strong> — count how many students cleared the bar. The lambda is a true/false rule.</li><li><strong>(passedCount * 100) / students.size</strong> — the same percentage calculation from Day 7. Multiply first, then divide, to avoid Day 5’s integer-division surprise.</li></ul><p>Now print them. Notice the safe-access pattern for highest and lowest:</p><pre>println(&quot;------------------- SUMMARY ------------------------&quot;)<br>    println(&quot;Class average:     %.1f&quot;.format(average))<br>    println(&quot;Highest score:     ${highest?.second} (${highest?.first})&quot;)<br>    println(&quot;Lowest score:      ${lowest?.second} (${lowest?.first})&quot;)<br>    println(&quot;Passed (&gt;= $passingMark):    $passedCount of ${students.size}&quot;)<br>    println(&quot;Pass rate:         $passRate%&quot;)<br>    println()</pre><p>A couple of new things:</p><ul><li><strong>&quot;%.1f&quot;.format(average)</strong> — formats the average to one decimal place (so 72.375 becomes 72.4). You saw this on Day 15.</li><li><strong>highest?.second</strong> — the safe-call operator from Day 8. Because maxByOrNull returns nullable, we use ?. to safely read .second. If the list were empty, this would print null instead of crashing.</li></ul><p>In real code you’d probably use Elvis (?:) here too, but for this report we’ll trust that the list is non-empty.</p><h3>Step 4: Grade Distribution</h3><p>This is where when shines. We want to count how many students fall into each grade band — A, B, C, or F.</p><p>There are a few ways to do this. Here’s a clean one using a helper function:</p><pre>fun gradeFor(score: Int): String = when {<br>    score &gt;= 90 -&gt; &quot;A&quot;<br>    score &gt;= 70 -&gt; &quot;B&quot;<br>    score &gt;= 50 -&gt; &quot;C&quot;<br>    else        -&gt; &quot;F&quot;<br>}</pre><p>Add that <strong>outside</strong> of main (functions live at the file level, not nested — Day 12 rule). Now we can map each student to their grade and count how many got each:</p><pre>val grades = students.map { gradeFor(it.second) }<br>    val aCount = grades.count { it == &quot;A&quot; }<br>    val bCount = grades.count { it == &quot;B&quot; }<br>    val cCount = grades.count { it == &quot;C&quot; }<br>    val fCount = grades.count { it == &quot;F&quot; }</pre><pre>    println(&quot;----------------- GRADE BREAKDOWN ------------------&quot;)<br>    println(&quot;A (90+):   $aCount students&quot;)<br>    println(&quot;B (70-89): $bCount students&quot;)<br>    println(&quot;C (50-69): $cCount students&quot;)<br>    println(&quot;F (&lt; 50):  $fCount students&quot;)<br>    println()</pre><p>Walk through what’s happening:</p><ol><li>students.map { gradeFor(it.second) } — for each student, run their score through gradeFor and collect the letters into a new list. Yesterday’s lambda + a function we just wrote.</li><li>grades.count { it == &quot;A&quot; } — count how many letters in that list equal &quot;A&quot;. Repeat for each grade.</li></ol><p>Notice how naturally map and count cooperate — that’s the magic of collection operations. The shape of the data transforms through each step.</p><blockquote>There’s a slicker way to do this — students.groupingBy { gradeFor(it.second) }.eachCount() builds the whole tally in one expression. It’s more advanced and we’ll meet groupingBy properly later. For now, the four-counter version is clearer and uses only what we’ve covered.</blockquote><h3>Step 5: Top 3 Students</h3><p>Final section. We want to find the three highest-scoring students and print them in order. Time for Day 15’s sortedByDescending:</p><pre>val topThree = students.sortedByDescending { it.second }.take(3)</pre><pre>    println(&quot;----------------- TOP 3 STUDENTS -------------------&quot;)<br>    topThree.forEachIndexed { index, student -&gt;<br>        val rank = index + 1<br>        println(&quot;$rank. ${student.first.padEnd(10)} —  ${student.second}&quot;)<br>    }</pre><p>Two new things here, both small:</p><ul><li><strong>.take(3)</strong> — keeps just the first 3 items of the (now-sorted) list. There’s also .drop(n) for the opposite. Both are useful.</li><li><strong>forEachIndexed { index, student -&gt; ... }</strong> — like forEach, but each iteration also gets the position. Same flavor as withIndex() from Day 10, but as a method.</li><li><strong>student.first.padEnd(10)</strong> — adds spaces to the right so names line up neatly in columns. Same kind of trick as Day 11’s padStart.</li></ul><h3>The Full Program</h3><p>Here’s everything stitched together. <strong>Type it out yourself.</strong> This one’s long enough that typing reveals which pieces you understand and which you skimmed.</p><pre>fun gradeFor(score: Int): String = when {<br>    score &gt;= 90 -&gt; &quot;A&quot;<br>    score &gt;= 70 -&gt; &quot;B&quot;<br>    score &gt;= 50 -&gt; &quot;C&quot;<br>    else        -&gt; &quot;F&quot;<br>}</pre><pre>fun main() {<br>    val className = &quot;Kotlin Foundations - Section A&quot;<br>    val passingMark = 50</pre><pre>    val students = listOf(<br>        &quot;Kiruba&quot;   to 88,<br>        &quot;Anuki&quot;    to 95,<br>        &quot;Sahan&quot;    to 48,<br>        &quot;Tharushi&quot; to 84,<br>        &quot;Pasindu&quot;  to 72,<br>        &quot;Nimal&quot;    to 61,<br>        &quot;Lakshmi&quot;  to 79,<br>        &quot;Ravi&quot;     to 52<br>    )</pre><pre>    println(&quot;============= CLASS PERFORMANCE REPORT =============&quot;)<br>    println(&quot;Class: $className&quot;)<br>    println(&quot;Students enrolled: ${students.size}&quot;)<br>    println()</pre><pre>    val average = students.map { it.second }.average()<br>    val highest = students.maxByOrNull { it.second }<br>    val lowest = students.minByOrNull { it.second }<br>    val passedCount = students.count { it.second &gt;= passingMark }<br>    val passRate = (passedCount * 100) / students.size</pre><pre>    println(&quot;------------------- SUMMARY ------------------------&quot;)<br>    println(&quot;Class average:     %.1f&quot;.format(average))<br>    println(&quot;Highest score:     ${highest?.second} (${highest?.first})&quot;)<br>    println(&quot;Lowest score:      ${lowest?.second} (${lowest?.first})&quot;)<br>    println(&quot;Passed (&gt;= $passingMark):    $passedCount of ${students.size}&quot;)<br>    println(&quot;Pass rate:         $passRate%&quot;)<br>    println()</pre><pre>    val grades = students.map { gradeFor(it.second) }<br>    val aCount = grades.count { it == &quot;A&quot; }<br>    val bCount = grades.count { it == &quot;B&quot; }<br>    val cCount = grades.count { it == &quot;C&quot; }<br>    val fCount = grades.count { it == &quot;F&quot; }</pre><pre>    println(&quot;----------------- GRADE BREAKDOWN ------------------&quot;)<br>    println(&quot;A (90+):   $aCount students&quot;)<br>    println(&quot;B (70-89): $bCount students&quot;)<br>    println(&quot;C (50-69): $cCount students&quot;)<br>    println(&quot;F (&lt; 50):  $fCount students&quot;)<br>    println()</pre><pre>    val topThree = students.sortedByDescending { it.second }.take(3)</pre><pre>    println(&quot;----------------- TOP 3 STUDENTS -------------------&quot;)<br>    topThree.forEachIndexed { index, student -&gt;<br>        val rank = index + 1<br>        println(&quot;$rank. ${student.first.padEnd(10)} —  ${student.second}&quot;)<br>    }<br>}</pre><p>Run it. You should see the full report print exactly like the example at the top of this article.</p><p>🎉 You just shipped your third real Kotlin program — and this one used <strong>every major topic from the past nine days.</strong></p><h3>Try Different Class Sizes</h3><p>This is the test that proves your code works for more than just our example:</p><ul><li><strong>One student</strong> — does the program still produce a sensible report?</li><li><strong>All passing scores</strong> (everyone above 80) — does the F count cleanly show 0 students?</li><li><strong>All failing scores</strong> (everyone below 30) — does the report stay coherent?</li><li><strong>Two students with the same top score</strong> — which one does maxByOrNull pick? (Hint: ties go to whichever appears first.)</li><li><strong>A larger list</strong> — copy-paste to make 20 or 30 students and watch the program scale without modification.</li></ul><p>Each test takes 5 seconds. Each one teaches you something about the robustness of what you wrote.</p><h3>What This Project Just Proved</h3><p>Concept</p><p>Where it appeared</p><p>Custom function with when body</p><p>gradeFor</p><p>Single-expression function</p><p>gradeFor uses = not { return ... }</p><p>Pair with to</p><p>Every student in the list</p><p>String templates</p><p>Every println line</p><p>map { ... }</p><p>Pulling out scores, mapping to grades</p><p>count { ... }</p><p>Pass count and grade breakdowns</p><p>maxByOrNull / minByOrNull</p><p>Highest and lowest scorer</p><p>Safe call ?.</p><p>Accessing nullable result fields</p><p>average()</p><p>Class average</p><p>sortedByDescending { ... }</p><p>Top 3 ranking</p><p>.take(n)</p><p>Keeping just the top 3</p><p>forEachIndexed</p><p>Numbered output</p><p>padEnd / format string</p><p>Column alignment</p><p>Lambdas with it</p><p>Every operation that takes a rule</p><p><strong>Fourteen patterns. One program. Nine days of learning compounding into a real utility.</strong></p><p>If you had been told on Day 7 that a couple of weeks later you’d be writing code like students.sortedByDescending { it.second }.take(3) <em>and reading it fluently</em>, you might not have believed it. But here we are.</p><h3>💪 Today’s Practice Challenge</h3><p><strong>Make it yours.</strong> Pick at least three:</p><ol><li>Replace the students list with <strong>your own data</strong> — could be real classmates, fictional names, fruit-and-prices, anything with names + numbers</li><li>Add a <strong>median</strong> calculation (sort the scores, pick the middle one — careful with even-sized lists)</li><li>Add a <strong>standard deviation</strong> or <strong>score range</strong> (max − min) to the summary</li><li>Change the <strong>passing mark</strong> to a different value via the variable at the top — the whole report should adjust automatically. (If it doesn’t, find the hard-coded number and replace it.)</li><li>Add a <strong>“struggling students”</strong> section that lists everyone scoring below the pass mark</li><li>Add a fifth grade band — A+ for 95+, then A for 90–94</li></ol><p><strong>Bonus challenges:</strong></p><ul><li>Make gradeFor take a <strong>threshold map</strong> as a parameter so you can customize the grade scale per call (hint: mapOf(&quot;A&quot; to 90, &quot;B&quot; to 70, ...))</li><li>Use groupingBy { ... }.eachCount() to replace the four count lines in Step 4 with one expression. Look it up in <a href="https://kotlinlang.org/docs/collection-grouping.html">the docs</a> — it’s a small read.</li><li>Add a printStudentReport(students: List&lt;Pair&lt;String, Int&gt;&gt;, className: String, passingMark: Int = 50) function that wraps the whole report. Now you can generate a report for any class with one call.</li><li><strong>Stretch:</strong> Build a second students list (Section B) and call printStudentReport twice. Watch how a single function reused twice replaces two giant copy-pasted blocks. That’s the real productivity gain of functions.</li></ul><h3>🎓 Practice Beyond This Article</h3><p>The <a href="https://play.kotlinlang.org/koans/overview"><strong>Kotlin Koans — Collections</strong></a> tasks are still excellent reps. By now you should be able to solve most of the introductory ones in a few minutes each.</p><h3>👉 Tomorrow: Day 18</h3><p>You’ve been writing programs that work with simple values — numbers, strings, booleans, lists of those. Tomorrow we add the most important tool for organizing more complex data: <strong>classes</strong>. Instead of representing a student as a Pair&lt;String, Int&gt; and accessing scores via .second, you’ll build a proper Student type with name and score as named properties. It’s the most important concept of Phase 1’s second half, and it changes how you think about modeling data.</p><p><strong>See you tomorrow.</strong></p><h3>📚 Series Navigation</h3><p><strong>Previous:</strong> Day 16 — Lambdas Explained <em>(link)</em> <strong>You are here:</strong> Day 17 — Mini Project #3: Student Grade Analyzer <strong>Next:</strong> Day 18 — Classes in Kotlin <em>(link coming tomorrow)</em></p><p>If this article helped, a clap or share means the world. It tells Medium to surface this series to more learners.</p><h3>📊 References &amp; Further Reading</h3><ul><li><a href="https://kotlinlang.org/docs/collection-aggregate.html">Official Kotlin docs — Collection aggregate operations</a></li><li><a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-pair/">Kotlin docs — Pair and Triple</a></li><li><a href="https://kotlinlang.org/docs/collection-grouping.html">Kotlin docs — Collection grouping (for the bonus challenge)</a></li><li><a href="https://play.kotlinlang.org/koans/overview">Kotlin Koans (free beginner exercises)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0dedce0d8d5d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>