Learn Kotlin Β· 18/18

Real-World Kotlin: Interop and Tooling

10 min read

Hey there, future Kotlin pro! πŸ‘‹ Welcome to the real-world side of Kotlin where we get our hands dirty with the tools and techniques that make Kotlin a joy to use in professional projects. We're going to explore how Kotlin plays nicely with its older sibling, Java, how to manage our projects with Gradle, and then dive into the essential practices of testing our code to make sure it's bug-free and ready for the world. Let's get this show on the road! πŸš€


1. Java Interoperability: Calling Java from Kotlin and Vice Versa β˜•πŸ€

The What and The Why

First off, what in the world is "interoperability"? πŸ€” In simple terms, it's the ability of Kotlin and Java code to talk to each other, to work together in the same project as if they were best friends.

The Problem: Imagine you're working on a huge project that's been written in Java for years. Rewriting the entire thing in Kotlin would be like trying to rebuild a skyscraper brick by brick while people are still living in it – not a great idea. πŸ˜… You need a way to start writing new features in modern, shiny Kotlin without breaking all the existing Java code.

The Solution: Kotlin was designed from day one to be 100% interoperable with Java. This means you can have both .java and .kt files in the same project, and they can call each other seamlessly. It's like having a universal translator built right into the language.

Calling Java from Kotlin

This is where you'll spend most of your time initially. You have a bunch of Java classes, and you want to use them from your new Kotlin code.

Let's imagine we have a simple Java class:

java
// User.java
public class User {
    private final String name;
    private int age;

    public User(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public static String getPlatform() {
        return "Java";
    }
}

Now, let's use this User class from a Kotlin file. It feels almost exactly like using a native Kotlin class!

kotlin
// App.kt
fun main() {
    // Create an instance of the Java class
    val user = User("Alice")

    // Use the getter for the name property
    println("Name: ${user.name}") // See? No need for user.getName()!

    // Use the setter for the age property
    user.age = 30 // So clean, right? No user.setAge(30) needed.

    println("Age: ${user.age}")

    // Calling a static method
    val platform = User.getPlatform()
    println("Platform: $platform")
}

Under the Hood: How does this magic work? The Kotlin compiler is smart. When it sees a Java class, it recognizes the getX() and setX() methods and exposes them as a property x in Kotlin. This is called property access syntax. For a getName() it creates a name property, and for getAge() and setAge() it creates a mutable age property.

A Funny Little Thing about Keywords: What if a Java method has a name that's a keyword in Kotlin, like is or when? No problem! You can call it by wrapping the name in backticks. For example, user.isNew() would work just fine.

Calling Kotlin from Java

Now, let's flip the script. You've written a cool new class in Kotlin, and you need to use it from your existing Java code.

Here's our Kotlin class:

kotlin
// Car.kt
class Car(val make: String, var year: Int) {
    fun startEngine() {
        println("Vroom!")
    }

    companion object {
        @JvmStatic
        fun getTopSpeed(): Int {
            return 200
        }
    }
}

And here's how you'd use it from Java:

java
// Main.java
public class Main {
    public static void main(String[] args) {
        // Creating an instance of the Kotlin class
        Car car = new Car("Toyota", 2023);

        // Accessing properties
        System.out.println("Make: " + car.getMake()); // We use the generated getter
        car.setYear(2024); // And the generated setter
        System.out.println("Year: " + car.getYear());

        // Calling a method
        car.startEngine();

        // Calling the companion object method
        int topSpeed = Car.getTopSpeed();
        System.out.println("Top Speed: " + topSpeed);
    }
}

What's Happening Here? The Kotlin compiler generates the standard Java-style getMake(), getYear(), and setYear(int year) methods for the Java side to use.

That @JvmStatic thing: In Kotlin, companion object is where we put things that are like Java's static members. For Java to see a method inside a companion object as a true static method, we need to give it a little hint with the @JvmStatic annotation. Without it, you'd have to write Car.Companion.getTopSpeed(), which is a bit clunky.


2. Gradle for Kotlin: Understanding the Build System πŸ—οΈ

The What and The Why

What is a build system? Imagine you're assembling a complex piece of furniture. You have screws, panels, and a set of instructions. A build system, like Gradle, is your set of instructions and the magical tool that puts everything together correctly.

The Problem: Modern applications aren't just one file of code. They have dependencies (other people's code you're using), different parts (like the main application and the test code), and need to be compiled, tested, and packaged. Doing all this by hand would be a tedious and error-prone nightmare.

The Solution: Gradle is a build automation tool that handles these tasks for you. You write a script that defines your project's needs, and Gradle does the rest. For Kotlin projects, we can use the Kotlin DSL (Domain Specific Language), which lets us write our build scripts in Kotlin!

The build.gradle.kts file

This file is the heart of your Gradle project. It's where you tell Gradle everything about your project. To use the Kotlin DSL, your Gradle files should end with .gradle.kts.

Here's a simple build.gradle.kts for a Kotlin project:

kotlin
// build.gradle.kts

plugins {
    kotlin("jvm") version "1.9.22" // 1. Apply the Kotlin plugin
}

repositories {
    mavenCentral() // 2. Where to find dependencies
}

dependencies {
    testImplementation(kotlin("test")) // 3. What dependencies to use
}

Let's break it down:

  1. plugins: This tells Gradle what kind of project you have. kotlin("jvm") indicates a Kotlin project for the Java Virtual Machine.
  2. repositories: This tells Gradle where to find external libraries (dependencies). mavenCentral() is a popular repository of Java and Kotlin libraries.
  3. dependencies: Here, you list all the external libraries you need. testImplementation(kotlin("test")) adds the Kotlin test library, but only for running tests.

Getting Started: The easiest way to start a new Kotlin project with Gradle is by using an IDE like IntelliJ IDEA. It has a project wizard that generates the build.gradle.kts file and project structure for you. Just go to File > New > Project, select Kotlin, and choose Gradle as the build system.


3. Unit Testing with JUnit and Kotlin πŸ§ͺ

The What and The Why

What is unit testing? It's the practice of testing the smallest, isolated pieces of your code (the "units") to ensure they work as expected. Think of it as checking each individual part of a machine before assembling the whole thing.

The Problem: You've written a function to calculate the total price of a shopping cart. It seems to work. But what about edge cases, like an empty cart, an item with a negative price, or a quantity of zero? These are easy to miss and can lead to bugs.

The Solution: By writing unit tests, you programmatically check all these scenarios. This gives you confidence that your code works correctly and helps you catch bugs early.

Setting up JUnit

JUnit 5 is the standard testing framework for Java and works great with Kotlin. To use it, add the dependency to your build.gradle.kts:

kotlin
// build.gradle.kts
dependencies {
    testImplementation(kotlin("test"))
}

tasks.withType<Test> {
    useJUnitPlatform()
}

Writing Your First Test

Let's say we have a simple Calculator class:

kotlin
// src/main/kotlin/Calculator.kt
class Calculator {
    fun add(a: Int, b: Int): Int {
        return a + b
    }
}

Now, let's write a test for the add method. By convention, test files go in the src/test/kotlin directory.

kotlin
// src/test/kotlin/CalculatorTest.kt
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test

class CalculatorTest {

    @Test
    fun `it should return the sum of two numbers`() {
        // Arrange: Set up the test
        val calculator = Calculator()

        // Act: Call the method to test
        val result = calculator.add(5, 10)

        // Assert: Check if the result is as expected
        assertEquals(15, result)
    }
}

Let's break this down:

  • @Test: This annotation tells JUnit that this function is a test case to be executed.
  • Function Name with Backticks: Kotlin allows you to use backticks for function names, which is great for writing descriptive test names that read like sentences.
  • Arrange, Act, Assert: A common pattern for structuring tests:
    • Arrange: Set up preconditions and inputs.
    • Act: Call the function being tested.
    • Assert: Check if the outcome is what you expected. assertEquals is a common assertion.

You can run your tests from your IDE (look for a green play icon) or by running ./gradlew test in your terminal.


4. Mocking Dependencies with MockK 🎭

The What and The Why

What is mocking? In testing, a "mock" is a simulated object that mimics the behavior of a real one.

The Problem: You want to test a piece of code in isolation. But what if that code depends on something complex, like a database or a web service? In a unit test, you don't want to connect to a real database or make a network call. That would be slow, unreliable, and wouldn't be an isolated test.

The Solution: You can mock the dependency. You create a fake version of it that you control completely. You can tell your mock, "When this method is called, return this specific value."

Introducing MockK

MockK is a powerful mocking library specifically for Kotlin. It uses Kotlin's features to provide a clean and expressive way to create mocks.

Getting Started: First, add the MockK dependency to your build.gradle.kts:

kotlin
// build.gradle.kts
dependencies {
    testImplementation("io.mockk:mockk:1.13.11")
}

A Practical Example

Imagine a NotificationService that depends on an EmailClient to send emails.

kotlin
// The dependency we want to mock
interface EmailClient {
    fun sendEmail(to: String, subject: String, body: String)
}

// The class we want to test
class NotificationService(private val emailClient: EmailClient) {
    fun notifyUser(email: String, message: String) {
        emailClient.sendEmail(email, "Notification", message)
    }
}

We want to test NotificationService without sending an email. So, we'll mock the EmailClient.

kotlin
// src/test/kotlin/NotificationServiceTest.kt
import io.mockk.mockk
import io.mockk.verify
import org.junit.jupiter.api.Test

class NotificationServiceTest {

    @Test
    fun `it should send a notification email`() {
        // Arrange
        val mockEmailClient = mockk<EmailClient>(relaxed = true) // 1. Create a mock
        val notificationService = NotificationService(mockEmailClient)

        // Act
        notificationService.notifyUser("[email protected]", "Your order has shipped!")

        // Assert / Verify
        verify(exactly = 1) { // 2. Verify the mock was called
            mockEmailClient.sendEmail(
                to = "[email protected]",
                subject = "Notification",
                body = "Your order has shipped!"
            )
        }
    }
}

Let's dissect this:

  1. mockk<EmailClient>(relaxed = true): This creates a mock of the EmailClient. relaxed = true is useful for mocks where you don't need to stub every single function.
  2. verify { ... }: This is how you check interactions. After calling our method, we verify that it called the sendEmail method on our mock with the correct arguments. verify(exactly = 1) ensures it was called precisely once.

Mocking is a powerful technique that allows you to test complex systems by breaking them down into small, manageable, and isolated units.


And that's a wrap on our tour of real-world Kotlin tooling and practices! You've learned how Kotlin and Java can be best buddies, how Gradle builds your projects, and how to write solid tests with JUnit and MockK. Now go out there and build something amazing! πŸŽ‰

Extra Reading & References

  • Kotlin-Java Interop:
    • Official Kotlin Documentation on Java Interoperability
    • Android Developers Guide to Interop
  • Gradle:
    • Gradle User Manual
    • Getting started with Gradle and Kotlin/JVM
  • JUnit 5:
    • JUnit 5 User Guide
  • MockK:
    • MockK Official Website

Challenge

You are working on a Kotlin application that integrates with a legacy Java email service. Your task is to write a unit test for the Notifier service to ensure it correctly formats and sends a welcome email through the JavaEmailGateway.

You have the following classes defined in your project:

Kotlin Data Class:

kotlin
data class User(val id: Int, val name: String, val email: String)

Kotlin Service:

kotlin
class Notifier(private val emailGateway: JavaEmailGateway) {
    fun sendWelcomeEmail(user: User) {
        val subject = "Welcome, ${user.name}!"
        val body = "Hi ${user.name}, welcome to our platform."
        emailGateway.send(user.email, subject, body)
    }
}

Legacy Java Gateway:

java
public class JavaEmailGateway {
    public void send(String to, String subject, String body) {
        // Simulates sending an email
        System.out.println("Email sent to " + to);
    }
}

Your Task

Write a complete JUnit 5 test class named NotifierTest. This class should contain a single test to verify the behavior of the Notifier.sendWelcomeEmail method.

Requirements:

  1. The test class must be named NotifierTest.
  2. Create one test method with the descriptive name `should call email gateway with correctly formatted arguments`.
  3. Use MockK to create a mock of the JavaEmailGateway.
  4. In the test, instantiate the Notifier class, passing the mocked gateway to its constructor.
  5. Create a sample User object (e.g., name "Alice", email "[email protected]").
  6. Call the sendWelcomeEmail method.
  7. Use MockK's verify block to confirm that the send method on your mock gateway was called exactly once with the correct email, subject, and body for the sample user.

Expected result

Your solution should be a complete Kotlin class NotifierTest.

The class must contain a single function annotated with @Test and named `should call email gateway with correctly formatted arguments`.

Inside this function, you should follow the Arrange-Act-Verify pattern:

  1. Arrange:
    • Create a mock instance of JavaEmailGateway using mockk<JavaEmailGateway>().
    • Create an instance of Notifier, injecting the mock gateway.
    • Create a sample User instance, for example: val user = User(1, "Alice", "[email protected]").
  2. Act:
    • Call the notifier.sendWelcomeEmail(user) method.
  3. Verify:
    • Use verify(exactly = 1) { ... } to check that the send method on the mock gateway was called precisely one time.
    • The arguments passed to send must match the data from the sample User object, like so: gateway.send("[email protected]", "Welcome, Alice!", "Hi Alice, welcome to our platform.").
kotlin

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.