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
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
- 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
Install and check
- Install IntelliJ IDEA or Android Studio (Kotlin is included), or the kotlinc compiler from the official Kotlin releases.
- Check:
kotlinc -version(command line) or create a new Kotlin project in the IDE. - In Gradle projects, add
testImplementation(kotlin("test"))and run./gradlew test.
Step 1 — the 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
# -> 10379Step 3 — ask for tests, then run them
Write kotlin.test checks for emi: 5 lakh at 9% for 60 months, zero interest, negative principal, and zero months.
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 passedSettings and config
- Rules file: “Kotlin 2.x, null-safety, no !!, kotlin.test/JUnit, coroutines for async”.
- Turn on warnings as errors in CI:
kotlin { compilerOptions { allWarningsAsErrors.set(true) } }in Gradle. - 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 (?.) orrequireNotNull. - Double for money — fine for an EMI estimate; use
BigDecimalfor 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.
नमस्कार मित्रांनो. Live chapter मध्ये Kotlin loan EMI helper आधीच आला आहे. हा सराव Nest Harbor नावाच्या वेगळ्या काल्पनिक स्टुडिओवर आहे. तुम्ही AI कडून seatBand हा Kotlin function मागता जो वय Child, Adult किंवा Senior मध्ये मॅप करतो, 0..120 बाहेरच्या वयांना IllegalArgumentException देतो, आणि प्रत्येक cutoff सिद्ध करतो. या drafting मशीनवर kotlinc नाही, म्हणून आम्ही Kotlin compile केले नाही. OpenJDK /usr/lib/jvm खाली असू शकते, पण आम्ही Kotlin apt-install केले नाही. समान cases छोट्या Python behavioral twin ने pytest खाली सिद्ध केले: starter twin मध्ये 4 fail आणि 5 pass, आणि fixed twin मध्ये सर्व 9 पास.
नमस्ते दोस्तों. Live chapter में Kotlin loan EMI helper पहले आ चुका है. यह अभ्यास Nest Harbor नाम के अलग काल्पनिक स्टूडियो पर है. आप AI से seatBand नाम का Kotlin function मांगते हो जो उम्र को Child, Adult या Senior में मैप करे, 0..120 से बाहर उम्र पर IllegalArgumentException दे, और हर cutoff साबित करे. इस drafting मशीन पर kotlinc नहीं है, इसलिए हमने Kotlin compile नहीं किया. OpenJDK /usr/lib/jvm के नीचे हो सकता है, लेकिन हमने Kotlin apt-install नहीं किया. वही cases छोटे Python behavioral twin से pytest के तहत साबित किए: starter twin में 4 fail और 5 pass, और fixed twin में सभी 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.
Ravindra Bagale's Tip – मराठी
Prompt मध्ये exact age cutoffs आणि IllegalArgumentException substring 0 and 120 लिहा. Python twin ने आधी सिद्ध केले तरीही तुमच्या मशीनसाठी Kotlin test file जपून ठेवा.
Ravindra Bagale's Tip – हिंदी
Prompt में exact age cutoffs और IllegalArgumentException substring 0 and 120 लिखो. Python twin से पहले साबित करने पर भी अपनी मशीन के लिए Kotlin test file बचाए रखो।
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
- Create a project folder and open a terminal inside it.
- Optional twin setup: on macOS or Linux run
python3 -m venv .venv. On Windows runpy -3 -m venv .venv. - 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. - 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):
// 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):
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.txtWrite 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
- Save the starter Kotlin file and the test file in one project.
- Ask your AI assistant to fix the cutoffs and add validation with the IllegalArgumentException substring the tests search for.
- 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.
- 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.ktpackage 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
- Problem:
seatBand(13)still returnsChild. Fix: Child must end at exactly 12 inclusive, so age 13 belongs to Adult. - Problem:
seatBand(60)still returnsAdult. Fix: Senior must start at exactly 60 inclusive. - Problem:
seatBand(-1)returns a label instead of an exception. Fix: reject every age outside 0..120 and put the substring0 and 120in the message. - 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.
Name the age cutoffs in the prompt
Keep the exception substring stable
Prompt मध्ये age cutoffs सांगा
Exception substring स्थिर ठेवा
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
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.