Calling Java from Kotlin

It Just Works

Kotlin compiles to the same bytecode as Java, so every Java library (JDK, Spring, Android SDK, Retrofit, Guava) can be used directly. Kotlin adds some sugar:

  • Java getters/setters appear as properties: getName()/setName() → name; isActive() → isActive.
  • Java methods named like Kotlin keywords are escaped with backticks: mock.`when`(...), obj.`is`.
  • Java void becomes Unit; Java checked exceptions do not need to be caught.
  • Java collections are mapped to Kotlin List/MutableList types.

Example

Example

import java.time.LocalDate
import java.time.temporal.ChronoUnit
import java.util.Calendar
import java.util.concurrent.ConcurrentHashMap

fun main() {
    val joined = LocalDate.of(2023, 6, 15)
    println("Day: ${joined.dayOfWeek}, leap year: ${joined.isLeapYear}")   // getDayOfWeek(), isLeapYear()
    println("Days to 2024-01-01: ${ChronoUnit.DAYS.between(joined, LocalDate.of(2024, 1, 1))}")

    val cal = Calendar.getInstance()
    cal.timeInMillis = 0                       // setTimeInMillis(0)
    cal.set(2024, Calendar.AUGUST, 15)
    println("Month index: ${cal.get(Calendar.MONTH)}")

    val visits = ConcurrentHashMap<String, Int>()
    listOf("home", "cart", "home").forEach { visits.merge(it, 1, Int::plus) }
    println("Visits: ${visits.toSortedMap()}")

    val sb = java.lang.StringBuilder("avaj")
    println(sb.reverse())
}

Output

Day: THURSDAY, leap year: false
Days to 2024-01-01: 200
Month index: 7
Visits: {cart=1, home=2}
java