By testing our Kotlin code from Java, we can gain a better understanding of how the interop works between the two languages. This can shed some light on where and how we may want to modify our Kotlin APIs to be more friendly vis-à-vis Java clients.
Let's look at one example. In this code snippet, we've added a factory method to our Student class via a companion object:
data class Student(val firstName: String, val lastName: String) {
companion object {
fun createDefaultStudent() = Student("Jane", "Doe")
}
}
Then, we can validate the behavior of that factory method using tests written in Java or Kotlin. In the following code, we've written a test in Java to validate the behavior of createDefaultStudent():
public class StudentTest {
@Test
public void testCreateDefaultStudent() {
Student defaultStudent =
Student.Companion.createDefaultStudent();
assertEquals(defaultStudent.getLastName(), "Doe");
assertEquals(defaultStudent.getFirstName(), "Jane");
}
}
By writing this test in Java, we are able to examine how the use of the companion object impacts our API design. We can see that in order to use the createDefaultStudent() function, we must first reference the Companion class, which makes for a verbose and cumbersome API call. This is something we may not have noticed if we were only testing our Kotlin code using Kotlin itself.
In a code base using both Java and Kotlin, we may want to improve the syntax required when calling createDefaultStudent() from Java. In this case, we could modify the companion object to be named Factory. After doing so, our test looks something more like this:
@Test
public void testCreateDefaultStudent() {
Student defaultStudent = Student.Factory.createDefaultStudent();
assertEquals(defaultStudent.getLastName(), "Doe");
assertEquals(defaultStudent.getFirstName(), "Jane");
}
At the time of writing, if you're working in a code base with a lot of interplay between Java and Kotlin, then testing your Kotlin from Java can be an effective way of improving your APIs, rather than down the line when they are being used. Let's see how that works next!