DEV Community

Cover image for #TeachingKotlin Part 3 - Caveats coming from Java
Harsh Shandilya
Harsh Shandilya

Posted on • Originally published at msfjarvis.dev

#TeachingKotlin Part 3 - Caveats coming from Java

When you start migrating your Java code to Kotlin, you will encounter multiple subtle changes that might catch you off guard. I'll document some of these gotchas that I and other people I follow have found and written about.

Splitting strings

Java's java.lang.String#split method takes a String as it's first argument and creates a Regex out of it before attempting to split. Kotlin, however, has two variants of this method. One takes a String and uses it as a plaintext delimiter, and the other takes a Regex behaving like the Java method we mentioned earlier. Code that was directly converted from Java to Kotlin will fail to accommodate this difference, so be on the lookout.

Liquid error: internal

Runtime asserts

Square's Jesse Wilson found through an OkHttp bug that Kotlin's assert function differs from Java's in a very critical way - the asserted expression is always executed. He's written about it on his blog which you can check out for a proper write up: Kotlin’s Assert Is Not Like Java’s Assert.

TL; DR Java's assert checks the java.lang.Class#desiredAssertionStatus method before executing the expression, but Kotlin does it after which results in unnecessary, potentially significant overhead.

// Good :)
@Override void flush() {
  if (Http2Stream.class.desiredAssertionStatus()) {
    if (!Thread.holdsLock(Http2Stream.this) == false) {
      throw new AssertionError();
    }
  }
  ...
}
Enter fullscreen mode Exit fullscreen mode
// Bad :(
override fun flush() {
  if (!Thread.holdsLock(this@Http2Stream) == false) {
    if (Http2Stream::class.java.desiredAssertionStatus()) {
      throw AssertionError()
    }
  }
  ...
}
Enter fullscreen mode Exit fullscreen mode

Binary incompatibility challenges

Jake Wharton wrote in his usual in-depth detail about how the Kotlin data class modifier makes it a challenge to modify public API without breaking source and binary compatibility. Kotlin's sweet language features that provide things like default values in constructors and destructuring components become the very thing that inhibits binary compatibility.

Take about 10 minutes out and give Jake's article a read: Public API challenges in Kotlin.

Summary

While migrating from Java to Kotlin is great, there are many subtle differences between the languages that can blindside you and must be taken into account. It's more than likely that these problems may never affect you, but it's probably helpful to know what's up when they do :)

Latest comments (0)