How to use Kotlin in Java project

In the article Introduction to the Kotlin Language, I introduced Kotlin and promised to share my experience in the process of integrating Kotlin. This is one of the articles in that series.

First, we need a Java project, and I chose the project sample from the article Custom Exception and this repo!

Run the following commands (you can copy and run them at once):

1
2
3
4
5
# clone git sample repo
git clone https://gitlab.com/thanhtrixx/trile-dev-sample/
cd trile-dev-sample/
# copy to new project
cp -r custom-exception how-to-use-kotlin-in-java-project

Open the IDE. Here, I’m using IntelliJ IDEA CE and follow these steps:

1. Update Gradle build config

Rename the project (skip this step if you don’t need to rename it). Open the settings.gradle file and update it as follows:

1
rootProject.name = 'how-to-use-kotlin-in-java-project'

Add plugins in file build.gradle file:

1
2
// Apply the Kotlin JVM plugin to add support for Kotlin.
id 'org.jetbrains.kotlin.jvm' version "${kotlin_version}"

Similarly, update dependencies

1
2
3
4
// Reflection is a set of language and library features that allows you to introspect the structure of your program at runtime.
implementation 'org.jetbrains.kotlin:kotlin-reflect'
// Reflection is a set of language and library features that allows you to introspect the structure of your program at runtime.
implementation 'org.jetbrains.kotlin:kotlin-stdlib'

Add config for compileKotlin and build jar file

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
tasks.withType(KotlinCompile).configureEach {
  kotlinOptions {
    freeCompilerArgs = ['-Xjsr305=strict']
    jvmTarget = jdk_version
  }
}

sourceCompatibility = jdk_version

jar {
  // This line of code recursively collects and copies all of a project's files
  // and adds them to the JAR itself. One can extend this task, to skip certain
  // files or particular types at will
  from { configurations.compileClasspath.collect { it.isDirectory() ? it : zipTree(it) } }
  duplicatesStrategy(DuplicatesStrategy.EXCLUDE)
}

Finally, add gradle.properties:

1
2
kotlin_version=1.8.0
jdk_version=17

2. Kotlin call Java

Create a directory to store Kotlin class. The rule is that .kt files of Kotlin must be placed in the src/main/kotlin directory:

mkdir -p src/main/kotlin/dev/trile/java2kotlin

Create KotlinSalaryTransfer class with the provided content:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class KotlinSalaryTransfer {
  private val moneyTransfer = MoneyTransfer()
  private val salaryCalculator = SalaryCalculator()

  fun salaryTransfer(workingDay: Int, salaryPerDay: Int, accountNo: String?) {
    val salary = salaryCalculator.calcSalary(workingDay, salaryPerDay)
    moneyTransfer.transferMoney(accountNo, salary)
    println("Transfer Salary success")
  }
}

fun main(args: Array<String>) {
  val salaryTransfer = SalaryTransfer()
  try {
    salaryTransfer.salaryTransfer(args[0].toInt(), args[1].toInt(), args[2])
  } catch (e: NumberFormatException) {
    println("Parse int error " + e.message)
  } catch (e: SalaryException) {
    println(e.message)
  }
}
Build và chạy thử
# build
./gradlew clean build
# run
java -cp build/libs/*.jar dev.trile.java2kotlin.KotlinSalaryTransferKt 11 1000000 EM1

Please check the result to see if it matches the Custom Exception article ;))

3. Java call Kotlin

Rewrite the VietcomBank class using Kotlin kotlin:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class VietcomBank : Bank {

  @Throws(SalaryException::class)
  override fun transferMoney(accountNo: String, amount: Int) {
    checkTransferParams(accountNo, amount)

    if (amount > 10000000)
      throw SalaryException(ErrorType.TRANSFER_MONEY_NOT_ENOUGH_MONEY, "VCB only support transfer amount less than 10M")

    println("VCB Kotlin transfer success")
  }
}

Update MoneyTransfer to use the new VietcomBank class:

1
2
//  private final Bank vietcomBank = new VietcomBank();
private final Bank vietcomBank = new dev.trile.java2kotlin.VietcomBank();
Build and test
# build
./gradlew clean build
# run
java -cp build/libs/*.jar dev.trile.java2kotlin.KotlinSalaryTransferKt 5 1000000 EM1

The result will be updated as follows:

Transfer 5000000 to EM1
VCB Kotlin transfer success
Transfer Salary success

Conclusion: With this article, you will learn the first step to integrate Kotlin into Java, but the complete transition to Kotlin is a long journey. I will write a few more articles to make it easier for those who want to join me on this journey ;))

I updated the code sample in this repo. Thank you for reading this far.

Update: I have made updates to the content of build.gradle and gradle.properties to align with the development of Kotlin and Java.

updatedupdated2023-05-212023-05-21
Load Comments?