Ravindra BagaleCourses & study guides Track your progress
AI CODING ASSISTANTS · CHAPTER 3 · LANGUAGES

How to Code in Kotlin Using AI

Use an AI assistant to write a Kotlin function, run it, and prove it with tests. Kotlin is the main language for Android apps and also runs on servers.

In short: say the Kotlin version, give the formula or rules and one example with the exact answer, ask for kotlin.test tests, and run them.

Why Kotlin with AI

WHY

Kotlin is Google's preferred language for Android. Many Android teams write Kotlin every day. AI speeds up the repeated parts, but money and math must be checked with tests.

What you need

WHAT
  • JDK 17 or 21: Kotlin runs on the JVM.
  • Kotlin: through Android Studio or IntelliJ (bundled), or the kotlinc command-line compiler.
  • kotlin.test: Kotlin's test library; works with JUnit in Gradle projects.
  • IDE + assistant: Android Studio or IntelliJ with Copilot, or VS Code with Claude Code.

How it flows

1 · Describe the function formula + example answer 2 · AI writes code read every line 3 · Run it check the example 4 · Ask for tests edge cases 5 · Run tests all pass = keep

Install and check

HOW
  1. Install IntelliJ IDEA or Android Studio (Kotlin is included), or the kotlinc compiler from the official Kotlin releases.
  2. Check: kotlinc -version (command line) or create a new Kotlin project in the IDE.
  3. In Gradle projects, add testImplementation(kotlin("test")) and run ./gradlew test.

Step 1 — the prompt

COPY THIS PROMPT

Write a Kotlin function emi(principal: Double, annualRatePercent: Double, months: Int): Long for a loan EMI using EMI = P × r × (1+r)^n / ((1+r)^n − 1), where r is the monthly rate. Round to the nearest rupee. Zero interest means principal / months. Use require() for bad input. Example: emi(500000.0, 9.0, 60) = 10379. Only return the code.

Step 2 — the code (tested here)

Emi.kt
// Monthly loan EMI. Built with an AI assistant, then tested.
import kotlin.math.pow
import kotlin.math.roundToLong

/** EMI = P * r * (1+r)^n / ((1+r)^n - 1), r = monthly rate. Returns rupees, rounded. */
fun emi(principal: Double, annualRatePercent: Double, months: Int): Long {
    require(principal > 0) { "principal must be positive" }
    require(months > 0) { "months must be positive" }
    require(annualRatePercent >= 0) { "rate cannot be negative" }
    if (annualRatePercent == 0.0) return (principal / months).roundToLong()
    val r = annualRatePercent / 12 / 100
    val f = (1 + r).pow(months)
    return (principal * r * f / (f - 1)).roundToLong()
}

fun main() {
    println(emi(500_000.0, 9.0, 60))  // 10379
}
kotlinc Emi.kt -include-runtime -d emi.jar
java -jar emi.jar
# -> 10379

Step 3 — ask for tests, then run them

FOLLOW-UP PROMPT

Write kotlin.test checks for emi: 5 lakh at 9% for 60 months, zero interest, negative principal, and zero months.

EmiTest.kt
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith

fun main() {
    assertEquals(10379, emi(500_000.0, 9.0, 60))   // 5 lakh, 9%, 5 years
    assertEquals(10000, emi(120_000.0, 0.0, 12))   // zero interest
    assertFailsWith<IllegalArgumentException> { emi(-1.0, 9.0, 12) }
    assertFailsWith<IllegalArgumentException> { emi(100_000.0, 9.0, 0) }
    println("4 checks passed")
}
# -> 4 checks passed
Why the zero-interest case matters: the EMI formula divides by ((1+r)^n − 1). With 0% interest that is 0, and the answer becomes NaN. AI often forgets this. The test proves our code handles it.

Settings and config

  1. Rules file: “Kotlin 2.x, null-safety, no !!, kotlin.test/JUnit, coroutines for async”.
  2. Turn on warnings as errors in CI: kotlin { compilerOptions { allWarningsAsErrors.set(true) } } in Gradle.
  3. Use the IDE's “Reformat Code” after accepting AI code.

Watch out (common AI mistakes in Kotlin)

  • The !! operator — it crashes on null; ask for safe calls (?.) or requireNotNull.
  • Double for money — fine for an EMI estimate; use BigDecimal for real accounting.
  • Old Android APIs — say “Jetpack Compose” or your minSdk.
  • Blocking calls on the main thread — ask for coroutines.

Try this yourself: ask AI for a Kotlin seat band, then prove the cases

Hello friends. The live chapter already walked through a loan EMI helper in Kotlin. This practice is a different fictional studio called Nest Harbor. You ask an AI for a Kotlin function seatBand that maps guest ages to Child, Adult, or Senior, throws IllegalArgumentException for ages outside 0..120, and proves every cutoff. On this drafting machine there is no kotlinc, so we did not compile Kotlin. OpenJDK may exist under /usr/lib/jvm, but we did not apt-install Kotlin. We proved the same cases with a tiny Python behavioral twin under pytest: the starter twin failed 4 tests and passed 5, and the fixed twin passed all 9.

Ravindra Bagale's Tip

Put the exact age cutoffs and the IllegalArgumentException substring 0 and 120 in your prompt. Keep the Kotlin test file for your machine even when you first prove the same bands with the Python twin.

Practice label: Nest Harbor Studio, every age and every seat band here is fictional teaching data. It is not a real cinema or ticket system. Passing these tests proves only the listed cases.
Environment (tested): on 6 November 2026 this box had no kotlinc, and none was installed. OpenJDK 17 was present at /usr/lib/jvm/jdk-17.0.21+9 but was not used for this Kotlin draft. The same seat bands were proved with a Python twin under Python 3.13.5 and pytest 9.1.1. Starter twin: 4 failed, 5 passed. Fixed twin: 9 passed. Kotlin compile and JUnit were not run. The SeatBandTest.kt file is still the student-facing Kotlin test source.

Your task: start from the buggy SeatBand.kt that maps some ages but uses wrong cutoffs and skips validation. Ask an AI to match Child for 0..12, Adult for 13..59, and Senior for 60..120, throw IllegalArgumentException outside that range with a message containing 0 and 120, and keep the Kotlin test file for your machine. On machines without Kotlin yet, you may also use the Python twin.

Setup

HOW
  1. Create a project folder and open a terminal inside it.
  2. Optional twin setup: on macOS or Linux run python3 -m venv .venv. On Windows run py -3 -m venv .venv.
  3. Activate it: on macOS or Linux run source .venv/bin/activate. In Windows Command Prompt run .venv\Scripts\activate.bat, and in Windows PowerShell run .venv\Scripts\Activate.ps1.
  4. Install pytest inside the virtual environment: python -m pip install pytest.

Extra for Kotlin on your machine: install a Kotlin toolchain (kotlinc or Gradle with the Kotlin plugin), confirm the compiler version, and run SeatBandTest.kt. This drafting box did not have kotlinc and did not install one.

Starter SeatBand.kt (wrong cutoffs, skips validation):

SeatBand.kt
// Nest Harbor Studio seat band helper (fictional teaching cinema — not a real theater).
// Starter: returns a band for some ages but skips validation and wrong cutoffs.
package nestharbor

fun seatBand(age: Int): String {
    // Starter bugs: no range check; Child ends at 15; Senior starts at 65.
    if (age <= 15) return "Child"
    if (age < 65) return "Adult"
    return "Senior"
}

Simple tests SeatBandTest.kt (for your machine):

SeatBandTest.kt
package nestharbor

import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertThrows
import org.junit.jupiter.api.Test

class SeatBandTest {
    @Test fun childZero() = assertEquals("Child", seatBand(0))
    @Test fun childTwelve() = assertEquals("Child", seatBand(12))
    @Test fun adultThirteen() = assertEquals("Adult", seatBand(13))
    @Test fun adultFiftyNine() = assertEquals("Adult", seatBand(59))
    @Test fun seniorSixty() = assertEquals("Senior", seatBand(60))
    @Test fun seniorOneTwenty() = assertEquals("Senior", seatBand(120))
    @Test fun adultThirty() = assertEquals("Adult", seatBand(30))

    @Test
    fun rejectsNegative() {
        val ex = assertThrows(IllegalArgumentException::class.java) { seatBand(-1) }
        assert(ex.message!!.contains("0 and 120"))
    }

    @Test
    fun rejectsAboveOneTwenty() {
        val ex = assertThrows(IllegalArgumentException::class.java) { seatBand(121) }
        assert(ex.message!!.contains("0 and 120"))
    }
}

Python twin starter (optional local proof without Kotlin):

seat_band.py
"""Behavioral twin of Nest Harbor Studio seatBand (starter — buggy cutoffs)."""


def seat_band(age: int) -> str:
    if not isinstance(age, int) or isinstance(age, bool):
        raise TypeError("age must be an int")
    # Starter bugs: no range check; Child ends at 15; Senior starts at 65.
    if age <= 15:
        return "Child"
    if age < 65:
        return "Adult"
    return "Senior"

Suggested AI ask (copy and adapt):

kotlin-prompt.txt
Write a Kotlin function fun seatBand(age: Int): String in package nestharbor for fictional Nest Harbor Studio. Return Child for ages 0 through 12 inclusive, Adult for 13 through 59 inclusive, and Senior for 60 through 120 inclusive. Throw IllegalArgumentException with a message containing 0 and 120 for ages below 0 or above 120. Add simple JUnit tests covering the cutoffs and both rejection cases.

HOW to finish

HOW
  1. Save the starter Kotlin file and the test file in one project.
  2. Ask your AI assistant to fix the cutoffs and add validation with the IllegalArgumentException substring the tests search for.
  3. On a machine with Kotlin compile and run the tests. On this drafting box we used the Python twin instead: starter showed 4 failed and 5 passed.
  4. Run again after the fix. Expect 9 passed on the twin (or the matching Kotlin test count on your machine).

Real pytest twin output after the fixed twin:

pytest-after.txt
.........                                                                [100%]
9 passed in 0.01s
Optional completed SeatBand.kt (try it yourself first)

Your AI assistant may reorder the checks. Any version is fine if the Kotlin tests (or the Python twin) all pass.

SeatBand.kt
package nestharbor

fun seatBand(age: Int): String {
    if (age < 0 || age > 120) {
        throw IllegalArgumentException("age must be between 0 and 120")
    }
    if (age <= 12) return "Child"
    if (age <= 59) return "Adult"
    return "Senior"
}

Troubleshooting

HOW
  1. Problem: seatBand(13) still returns Child. Fix: Child must end at exactly 12 inclusive, so age 13 belongs to Adult.
  2. Problem: seatBand(60) still returns Adult. Fix: Senior must start at exactly 60 inclusive.
  3. Problem: seatBand(-1) returns a label instead of an exception. Fix: reject every age outside 0..120 and put the substring 0 and 120 in the message.
  4. Error: kotlinc is missing on the drafting box. Fix: use the Python twin here, or install Kotlin on your own machine without changing this server.

Practice cards: English and spoken Marathi

Each card below explains one idea on its own, so you can save or revise a single card without reading the whole chapter.

PRACTICE CARDAI Coding

Name the age cutoffs in the prompt

Ask for Child through 12, Adult through 59, and Senior through 120.
Run the tests and read which cutoffs still fail.
Ravindra Bagale · ravindrabagale.com/ai-coding
PRACTICE CARDAI Coding

Keep the exception substring stable

Tests search for 0 and 120 inside the IllegalArgumentException text.
Ask the AI to keep those words even if it rewrites the sentence.
Ravindra Bagale · ravindrabagale.com/ai-coding
सराव कार्डमराठी

Prompt मध्ये age cutoffs सांगा

12 पर्यंत Child, 59 पर्यंत Adult आणि 120 पर्यंत Senior मागा.
Tests चालवा आणि अजून fail होणारे cutoffs वाचा.
Ravindra Bagale · ravindrabagale.com/ai-coding
सराव कार्डमराठी

Exception substring स्थिर ठेवा

Tests IllegalArgumentException text मध्ये 0 and 120 शोधतात.
AI वाक्य बदलले तरीही ती शब्द ठेवायला सांगा.
Ravindra Bagale · ravindrabagale.com/ai-coding

Quick quiz

1. What is emi(500000.0, 9.0, 60)?

10379 rupees.

2. Why test 0% interest?

The formula divides by zero there; code must handle it separately.

3. Which Kotlin operator often causes crashes?

!! (not-null assertion).

4. Which type should real accounting use?

BigDecimal.

Save tokens and money

SMART AI USE

Give the formula in the prompt; the AI does not need to search or guess. Ask for one function plus tests. Paste only the top lines of a Gradle error.

Save these cards

INTERVIEW CARDAI Coding

How do you check AI Kotlin code?

Run the example; write kotlin.test tests.
Test edge cases like zero and negative input.
Ravindra Bagale · ravindrabagale.com/ai-coding
COMPARISON CARDAI Coding

Kotlin vs Java with AI

Kotlin: null-safety catches AI null bugs at compile time.
Java: needs extra null checks and tests.
Ravindra Bagale · ravindrabagale.com/ai-coding
REVISION CARDAI Coding

Kotlin with AI in 3

Formula + example in the prompt.
require() for bad input.
Tests incl. 0% interest.
Ravindra Bagale · ravindrabagale.com/ai-coding