Skip to main content

Programming languages · Beginner · 25 min

Use Kotlin null safety, data classes and extension functions

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Kotlin 2.4.21 · Eclipse Temurin JDK 25

You will build a small Kotlin 2.4 contact book that imports a CSV file using nullable types, data classes, extension functions, a sealed class, scope functions and collection operations, then call it from a Java file.

On this page

Java developers who open a Kotlin file for the first time tend to notice the same handful of things: question marks after type names, classes that are one line long, methods that seem to have been added to String, and when blocks with no default. Each one removes a kind of code Java makes you write by hand, or a kind of bug Java lets through.

In this tutorial you meet them by building one small program: a contact book that imports people from a CSV file, cleans up their phone numbers and prints a short report. You model a contact as a data class, handle missing phone numbers and emails with null safety, add phone and name helpers as extension functions on String, describe each import outcome with a sealed class, tidy up set-up code with scope functions, and query the book with collection operations. At the end you call the same compiled code from a plain Java file to see what Kotlin looks like from the other side.

You compile everything with kotlinc and run it with java, so there is no build tool to set up. If you have not installed the compiler yet, follow Hello World in Kotlin first; it covers the download, the checksum check and the -include-runtime flag used here.

Step 1 · Check your tools and make a demo folder

Check that Java and the Kotlin compiler both answer, then make a throwaway folder for the project:

Bash
java -version
kotlinc -version
mkdir -p ~/kotlin-contacts-demo
cd ~/kotlin-contacts-demo

Every program in this tutorial is a few .kt files compiled together into a JAR. The shared files (the contact model, the helpers, the importer) have no main function. Each step adds one small file that does have a main, so each JAR has exactly one place to start. Compiling takes several seconds each time, because the compiler runs on a JVM that has to start first.

Check it worked

java -version prints a line starting with something like openjdk version "25.0.5", kotlinc -version prints something like info: kotlinc-jvm 2.4.21, and pwd ends in kotlin-contacts-demo.

Step 2 · Model a contact with a data class

In Java, a class that only holds a name, a phone number, an email and a city needs a constructor, getters, equals, hashCode and toString, or a record. In Kotlin, it is this. Create Contact.kt:

Bash
cat > Contact.kt <<'KT'
data class Contact(
    val name: String,
    val phone: String?,
    val email: String? = null,
    val city: String? = null,
)
KT

The parentheses after the class name are the primary constructor, and val in front of each parameter makes it a read-only property as well. The data keyword tells the compiler to write equals, hashCode, toString, copy and one componentN function per property, all based on those four properties. String? means "a String or null"; you will use that in the next step. = null gives a parameter a default, so callers can leave it out.

Now try it. Create Copies.kt:

Bash
cat > Copies.kt <<'KT'
fun main() {
    val amara = Contact("Amara Obi", "0803 123 4567", city = "Lagos")
    val again = Contact("Amara Obi", "0803 123 4567", city = "Lagos")

    println(amara)
    println(amara == again)
    println(amara === again)

    val moved = amara.copy(city = "Abuja")
    println(moved)
    println(amara.city)

    val (name, phone) = moved
    println("$name: $phone")
}
KT
kotlinc Contact.kt Copies.kt -include-runtime -d copies.jar
java -cp copies.jar CopiesKt

What each line shows:

  • city = "Lagos" is a named argument. It skips email, which takes its default, without writing null in its place.
  • println(amara) uses the generated toString, so you see every property instead of Contact@1b6d3586.
  • == in Kotlin calls equals, which compares the properties, so two contacts with the same data are equal. === asks whether they are the same object in memory. This is the reverse of the habit Java teaches, where == on objects compares references.
  • copy(city = "Abuja") makes a new contact with one property changed. amara is untouched, which is why the next line still prints Lagos. Because every property is a val, a contact can never change after it is made, and copy is how you get an updated one.
  • val (name, phone) = moved is a destructuring declaration. It calls component1() and component2(), which follow the order of the constructor. Destructuring is handy for two or three values; for more, use the property names, because reordering the constructor silently changes what each variable holds.

The run command names CopiesKt. Kotlin puts the top-level functions of Copies.kt into a class named after the file, as Hello World in Kotlin showed. If you have used Java records, a data class plays the same role; Model data in Java with records and sealed interfaces covers the Java side.

Check it worked

The program prints six lines: the full contact with city=Lagos, then true, then false, the copy with city=Abuja, Lagos, and Amara Obi: 0803 123 4567. ls shows copies.jar.

Step 3 · Handle missing values with null safety

Some contacts have no phone, no email or no city. In Kotlin a plain String can never hold null, and the compiler stops you from using a String? as if it were a String. You have to say what happens when the value is missing. Create Nulls.kt:

Bash
cat > Nulls.kt <<'KT'
fun describe(contact: Contact): String {
    val phone = contact.phone ?: "no phone"
    val domain = contact.email?.substringAfter('@') ?: "no email"
    return "${contact.name}: $phone, $domain"
}

fun callLine(contact: Contact): String? =
    contact.phone?.let { number -> "Call ${contact.name} on $number" }

fun cityLength(contact: Contact): Int {
    val city = contact.city
    if (city == null) return 0
    return city.length
}

fun main() {
    val amara = Contact("Amara Obi", "0803 123 4567", "amara@example.com", "Lagos")
    val kofi = Contact("Kofi Mensah", null)

    println(describe(amara))
    println(describe(kofi))
    println(callLine(amara))
    println(callLine(kofi))
    println(cityLength(amara))
    println(cityLength(kofi))
}
KT
kotlinc Contact.kt Nulls.kt -include-runtime -d nulls.jar
java -cp nulls.jar NullsKt

Four tools are at work here:

  • The Elvis operator ?: gives a fallback. contact.phone ?: "no phone" is the phone if there is one, and "no phone" if it is null. The result is a plain String.
  • The safe call ?. calls a method only when the value is not null. contact.email?.substringAfter('@') is null when there is no email, so the whole chain falls through to the ?: on the right.
  • let runs a block with the value as its argument, here named number. Combined with ?., the block runs only for a contact that has a phone. Otherwise callLine returns null, which is why its return type is String? and why the fourth line prints null.
  • Smart casts: after if (city == null) return 0, the compiler knows city cannot be null on the next line, so city.length is allowed with no ?.. This works for local vals like city, which is why the function copies contact.city into one first.

There is also !!, as in contact.phone!!.length, which throws a NullPointerException if the value is null. It turns a compile-time question back into a run-time crash, so treat each !! as something to justify. In this project you never need one.

Check it worked

Amara's line shows her number and example.com. Kofi's shows no phone, no email. Then come Amara's call line, null for Kofi, 5 for the letters in Lagos, and 0 for Kofi, who has no city.

Step 4 · Add extension functions to String

Phone numbers arrive as 0803 123 4567, 024-412-3456 or +233 24 412 3456. You want one clean format, + and the country code followed by digits, and you want to call it as if String had always had the method. That is an extension function. Create Text.kt:

Bash
cat > Text.kt <<'KT'
fun String.normalisePhone(countryCode: String = "234"): String? {
    val digits = filter { it.isDigit() || it == '+' }
    return when {
        digits.startsWith("+") && digits.length >= 11 -> digits
        digits.startsWith("0") && digits.length in 10..11 -> "+$countryCode${digits.drop(1)}"
        else -> null
    }
}

fun String.initials(): String =
    split(' ').filter { it.isNotBlank() }.joinToString("") { it.first().uppercase() }

fun String?.orDash(): String = if (this.isNullOrBlank()) "-" else this
KT

fun String.normalisePhone(...) declares a function whose receiver is a String. Inside it, this is that string, and you can call its methods without a prefix, which is why filter { ... } works on its own. The function keeps digits and +, accepts numbers already in international form, turns a local number with a leading 0 into international form using a country code (Nigeria's 234 by default), and returns null for anything it cannot read.

initials builds AO from amara obi. orDash has a nullable receiver, String?, so you can call it on a value that might be null without ?.; it returns - for null or blank text. isNullOrBlank() also tells the compiler that this is not null in the else branch, so the smart cast from the previous step applies.

Try them. Create Ext.kt:

Bash
cat > Ext.kt <<'KT'
fun main() {
    println("0803 123 4567".normalisePhone())
    println("024-412-3456".normalisePhone(countryCode = "233"))
    println("+44 20 7946 0000".normalisePhone())
    println("12345".normalisePhone())
    println("amara obi".initials())

    val missing: String? = null
    println(missing.orDash())
    println("Lagos".orDash())
}
KT
kotlinc Text.kt Ext.kt -include-runtime -d ext.jar
java -cp ext.jar ExtKt

An extension does not change the String class. The compiler turns it into an ordinary static function that takes the string as its first argument, and decides which extension to call from the declared type at compile time. That has two consequences: an extension cannot read private members of the class, and if the class already has a method with the same name and parameters, the class's method wins.

These rules are deliberately simple. Country codes, number lengths and mobile prefixes vary across Nigeria, Ghana, Kenya and everywhere else, so a real app should use a maintained library such as Google's libphonenumber rather than rules written by hand. The point here is the shape: a small helper named after what it does, called where the data is.

Check it worked

The Nigerian number becomes +2348031234567, the Ghanaian one +233244123456, the UK number keeps its own code, and 12345 gives null. Then AO, a - for the missing value, and Lagos.

Step 5 · Describe each import with a sealed class and when

Importing a CSV line can go three ways: the contact is added, it is a duplicate, or the line is unusable. A sealed class lists every possible outcome, and the compiler uses that list to check your when blocks. Create Import.kt:

Bash
cat > Import.kt <<'KT'
sealed class ImportResult {
    data class Added(val contact: Contact) : ImportResult()
    data class Duplicate(val name: String) : ImportResult()
    data class Invalid(val line: Int, val reason: String) : ImportResult()
}

fun parseLine(lineNumber: Int, line: String, seen: Set<String>): ImportResult {
    val parts = line.split(',').map { it.trim() }
    val name = parts.getOrNull(0)
    if (name.isNullOrEmpty()) return ImportResult.Invalid(lineNumber, "no name")
    if (name.lowercase() in seen) return ImportResult.Duplicate(name)

    val rawPhone = parts.getOrNull(1)?.takeIf { it.isNotEmpty() }
    val phone = rawPhone?.normalisePhone()
    if (rawPhone != null && phone == null) {
        return ImportResult.Invalid(lineNumber, "bad phone '$rawPhone'")
    }

    return ImportResult.Added(
        Contact(
            name = name,
            phone = phone,
            email = parts.getOrNull(2)?.takeIf { it.isNotEmpty() },
            city = parts.getOrNull(3)?.takeIf { it.isNotEmpty() },
        )
    )
}

fun summary(result: ImportResult): String = when (result) {
    is ImportResult.Added -> "added ${result.contact.name}"
    is ImportResult.Duplicate -> "skipped ${result.name}: already in the book"
    is ImportResult.Invalid -> "line ${result.line}: ${result.reason}"
}
KT

Points to notice:

  • Each outcome is its own data class carrying the data that outcome needs. Added has a contact, Invalid has a line number and a reason. There is no shared type field and no properties that are null "because they do not apply to this kind".
  • parts.getOrNull(1) returns null instead of throwing when a line has fewer columns, and takeIf { it.isNotEmpty() } turns an empty column into null. Missing data becomes String?, and the null tools from earlier take over.
  • In summary, is ImportResult.Added -> checks the type and smart casts result inside that branch, so result.contact needs no cast.
  • The when has no else. Because ImportResult is sealed, the compiler knows these three cases are all there are.

Run it over a few sample lines. Create Imports.kt:

Bash
cat > Imports.kt <<'KT'
fun main() {
    val lines = listOf(
        "Amara Obi, 0803 123 4567, amara@example.com, Lagos",
        "Kofi Mensah, +233 24 412 3456, , Accra",
        "amara obi, 0803 123 4567, , Lagos",
        ", 0802 000 0000, , Ibadan",
        "Wanjiru Kamau, 0712, , Nairobi",
    )
    val seen = mutableSetOf<String>()
    for ((index, line) in lines.withIndex()) {
        val result = parseLine(index + 1, line, seen)
        if (result is ImportResult.Added) seen.add(result.contact.name.lowercase())
        println(summary(result))
    }
}
KT
kotlinc Contact.kt Text.kt Import.kt Imports.kt -include-runtime -d imports.jar
java -cp imports.jar ImportsKt

Now see the check that makes sealed classes worth using. Add a fourth outcome in a new file, as a teammate might months later:

Bash
cat > Skipped.kt <<'KT'
data class Skipped(val line: Int) : ImportResult()
KT

Compile again with it included:

Bash
kotlinc Contact.kt Text.kt Import.kt Skipped.kt -d check.jar

The build fails, pointing at the when in summary, because it has no branch for Skipped. With an else branch, it would have compiled and quietly sent the new case down the wrong path. Leave else out of when over a sealed type, so the compiler finds every place a new case needs handling. Remove the experiment before you carry on:

Bash
rm Skipped.kt

Check it worked

The import run prints five lines: two contacts added, the second Amara skipped as a duplicate even though the case differs, line 4 rejected for having no name, and line 5 rejected for the phone 0712. The build with Skipped.kt fails with an error something like 'when' expression must be exhaustive that names Import.kt, and ls shows no check.jar.

Step 6 · Use scope functions, with one rule for each

let, apply, also, run and with are scope functions: each runs a block of code with an object in reach. They differ in two ways, how the block refers to the object (this or it) and what the call returns (the object itself or the block's result). That is easy to mix up, so use one rule for each:

  • apply: set up an object you just created. Inside, the object is this; the call returns the object.
  • also: do something extra with a value, such as log or check it, without changing what flows on. Inside, the value is it; the call returns the value.
  • run: compute one result from an object. Inside, the object is this; the call returns the block's result.
  • let: work with a value only when it is not null, as x?.let { ... }. Inside, the value is it; the call returns the block's result.

with(obj) { ... } is run written as a normal function call; you can ignore it until you meet it in someone else's code. If you find yourself nesting one scope function inside another, use a named val instead. That is almost always easier to read.

First give the contacts somewhere to live. Create Book.kt:

Bash
cat > Book.kt <<'KT'
class ContactBook {
    private val contacts = mutableListOf<Contact>()

    val size: Int
        get() = contacts.size

    fun add(contact: Contact) {
        contacts.add(contact)
    }

    fun all(): List<Contact> = contacts.toList()

    fun find(name: String): Contact? =
        contacts.firstOrNull { it.name.equals(name, ignoreCase = true) }
}
KT

The list inside is mutable but private. all() hands out a copy typed as List<Contact>, Kotlin's read-only list, so code outside the book cannot add to it. find returns Contact?, because the name may not be there. Now use the four rules. Create Scopes.kt:

Bash
cat > Scopes.kt <<'KT'
fun main() {
    val book = ContactBook().apply {
        add(Contact("Amara Obi", "+2348031234567", city = "Lagos"))
        add(Contact("Kofi Mensah", "+233244123456", city = "Accra"))
    }

    val tunde = Contact("Tunde Bello", null, city = "Lagos")
        .also { println("Adding ${it.name}") }
    book.add(tunde)

    val line = book.run { "The book holds $size contacts" }
    println(line)

    book.find("kofi mensah")?.let { println("Found ${it.name} in ${it.city}") }

    val zainab = book.find("Zainab Musa")
    println(zainab?.name ?: "No Zainab Musa")
}
KT
kotlinc Contact.kt Book.kt Scopes.kt -include-runtime -d scopes.jar
java -cp scopes.jar ScopesKt

apply lets the two add calls skip the book. prefix and still hands back the book. also prints a line and passes Tunde through unchanged. run reads size as this.size and returns the sentence. ?.let runs only because Kofi was found. For Zainab, a plain ?. and ?: is clearer than another scope function.

Check it worked

You see Adding Tunde Bello, then The book holds 3 contacts, Found Kofi Mensah in Accra (the search ignores case), and No Zainab Musa.

Step 7 · Import a CSV file and query it with collection operations

Now put it together. Create a CSV file with a header row and some awkward lines: a contact with no phone, a duplicate, a bad number and a missing city:

Bash
cat > contacts.csv <<'CSV'
name,phone,email,city
Amara Obi,0803 123 4567,amara@example.com,Lagos
Kofi Mensah,+233 24 412 3456,kofi@example.org,Accra
Tunde Bello,,,Lagos
Amara Obi,0803 123 4567,,Lagos
Wanjiru Kamau,0712,,Nairobi
Zainab Musa,0816 555 0101,zainab@example.com,
Chinedu Eze,0705 222 3333,chinedu@example.org,Lagos
CSV

Then create App.kt, which imports the file and prints a report:

Bash
cat > App.kt <<'KT'
import java.io.File

fun main(args: Array<String>) {
    val path = args.firstOrNull() ?: "contacts.csv"
    val book = ContactBook()
    val seen = mutableSetOf<String>()
    val problems = mutableListOf<String>()

    val lines = File(path).readLines().drop(1)
    for ((index, line) in lines.withIndex()) {
        when (val result = parseLine(index + 2, line, seen)) {
            is ImportResult.Added -> {
                book.add(result.contact)
                seen.add(result.contact.name.lowercase())
            }
            is ImportResult.Duplicate, is ImportResult.Invalid -> problems.add(summary(result))
        }
    }

    val contacts = book.all()
    println("Imported ${contacts.size} contacts, ${problems.size} problems")
    problems.forEach { println("  $it") }

    println("By city:")
    contacts.groupBy { it.city.orDash() }
        .toSortedMap()
        .forEach { (city, people) ->
            println("  $city: ${people.map { it.name.initials() }.sorted().joinToString()}")
        }

    val (withPhone, withoutPhone) = contacts.partition { it.phone != null }
    println("With a phone: ${withPhone.size}, without: ${withoutPhone.size}")

    val domains = contacts.mapNotNull { it.email?.substringAfter('@') }.distinct().sorted()
    println("Email domains: ${domains.joinToString()}")

    val first = contacts.minByOrNull { it.name }
    println("First alphabetically: ${first?.name.orDash()}")
}
KT
kotlinc Contact.kt Text.kt Import.kt Book.kt App.kt -include-runtime -d contacts.jar
java -cp contacts.jar AppKt

drop(1) skips the header, and index + 2 turns list positions into file line numbers. when (val result = ...) declares result just for the when, and one branch can list two cases. The report then uses the collection functions that replace most loops in Kotlin code:

  • groupBy builds a map from a key to the items with that key. Contacts with no city land under -, thanks to orDash. toSortedMap() sorts by key, and forEach { (city, people) -> ... } destructures each map entry.
  • map turns each item into something else, here initials. sorted() and joinToString() finish the line.
  • partition splits one list into two by a condition and returns them as a pair, which destructures into two names.
  • mapNotNull maps and drops the nulls in one go, so contacts without an email simply do not appear. distinct() removes repeats.
  • minByOrNull returns the smallest item by a key, or null for an empty list, which is why first?.name needs ?..

None of these change contacts; each returns a new list or map. The program also takes a file path as its first argument, so java -cp contacts.jar AppKt other.csv imports a different file. Names in any script work, because Kotlin strings are Unicode, though initials() takes only the first character of each word.

Check it worked

The report says Imported 5 contacts, 2 problems and names the duplicate Amara and the bad phone on line 6. Under By city:, Zainab's initials sit under -, Kofi's under Accra, and three sets under Lagos. Then With a phone: 4, without: 1, two email domains and First alphabetically: Amara Obi.

Step 8 · Call the Kotlin code from Java

Kotlin compiles to the same bytecode as Java, so a Java file can use Contact, ContactBook and the helpers directly. Seeing how they look from Java shows what the Kotlin features turn into. Create Report.java:

Bash
cat > Report.java <<'JAVA'
import java.util.List;
import java.util.Set;

public class Report {
    public static void main(String[] args) {
        Contact amara = new Contact("Amara Obi", "+2348031234567", null, "Lagos");
        System.out.println(amara.getName() + " lives in " + amara.getCity());
        System.out.println(amara.equals(new Contact("Amara Obi", "+2348031234567", null, "Lagos")));
        System.out.println(amara.copy(amara.getName(), null, "amara@example.com", "Abuja"));

        System.out.println(TextKt.normalisePhone("0705 222 3333", "234"));
        System.out.println(TextKt.orDash(amara.getEmail()));

        ContactBook book = new ContactBook();
        book.add(amara);
        List<Contact> all = book.all();
        System.out.println("Book size from Java: " + book.getSize() + ", list size: " + all.size());

        ImportResult result = ImportKt.parseLine(1, "Kofi Mensah,0712,,Accra", Set.of());
        if (result instanceof ImportResult.Invalid invalid) {
            System.out.println("Invalid: " + invalid.getReason());
        }

        try {
            new Contact(null, null, null, null);
        } catch (NullPointerException e) {
            System.out.println("Kotlin rejected a null name: " + e.getClass().getSimpleName());
        }
    }
}
JAVA
javac -cp contacts.jar Report.java
java -cp contacts.jar:. Report

contacts.jar from the previous step holds your compiled classes and the Kotlin standard library, so it is all javac and java need. On Windows, write the class path as contacts.jar;. with a semicolon. What Java sees:

  • Properties are getters. name becomes getName(), and the computed size property becomes getSize().
  • Default arguments are gone. Java has no defaults, so it must pass all four constructor arguments and all four to copy. Adding @JvmOverloads to a Kotlin function or constructor generates the shorter Java overloads for you.
  • Extension functions are static methods on the file's class, TextKt, with the string as the first argument. A line @file:JvmName("Phones") at the top of Text.kt would rename that class.
  • Sealed subclasses are nested classes. ImportResult.Invalid works with Java's instanceof pattern.
  • Null safety is checked at the border. Java's compiler does not know about String versus String?, so Kotlin adds a run-time check to public functions and constructors that take non-null parameters. Passing null for name fails at once with a NullPointerException naming the parameter, rather than letting a null into a contact.

The other direction has its own catch. When Kotlin calls a Java method that has no nullability annotations, Kotlin cannot tell whether the result may be null, and treats it as a platform type, shown as String! in error messages. Give such values an explicit type (val x: String? = javaThing.getValue()) at the point they enter your Kotlin code, so null safety covers them from there on.

When you are finished, delete the demo folder. This removes only what you created in this tutorial:

Bash
cd ~
rm -rf ~/kotlin-contacts-demo

Keep the compiler for the next tutorials. To remove it, follow the last step of Hello World in Kotlin.

Check it worked

The Java program prints eight lines, ending with Invalid: bad phone '0712' and Kotlin rejected a null name: NullPointerException. The copy line shows phone=null and city=Abuja, and the phone line shows +2347052223333. After the clean-up, ls ~/kotlin-contacts-demo reports that there is no such file or directory.

The same ideas on Android

The features in this tutorial are the everyday ones in Android code, where Google recommends Kotlin for new apps. Screen state is often a data class updated with copy, the outcome of a network call is often a sealed class handled with an exhaustive when, and null safety catches the missing field before the app ships. Many Android users across Africa are on low-cost phones and prepaid data, where a crash or a failed sync costs them more, so a compiler that catches these mistakes early is worth having.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.