Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run Java to Kotlin converter from the command line?

You can use the Kotlin plug-ins for Intellij and Eclipse to convert Java files to Kotlin. Can this conversion be done from the command line some how without either of these IDEs?

like image 847
Travis Spencer Avatar asked Jul 18 '15 18:07

Travis Spencer


People also ask

How do I convert Java code to Kotlin?

To convert Java code to Kotlin, open the Java file in Android Studio, and select Code > Convert Java File to Kotlin File. Alternatively, create a new Kotlin file (File > New > Kotlin File/Class), and then paste your Java code into that file.

Can you migrate code from Java to Kotlin?

Kotlin programming language is fully compatible with Java code. It is easy to migrate from Java code to Kotlin language because of its compatibility. Therefore, when you are using Kotlin language in Android, you can easily run it from the Java code.


1 Answers

It seems that it's possible, but there's no tool for that, just code. There are tests in j2k module in Kotlin Github repository, the example below is taken from the tests (AbstractJavaToKotlinConverterSingleFileTest):

private fun fileToKotlin(text: String, settings: ConverterSettings, project: Project): String {
    val file = createJavaFile(text)
    val converter = JavaToKotlinConverter(project, settings,
                                          IdeaReferenceSearcher, IdeaResolverForConverter)
    return converter.filesToKotlin(listOf(file), J2kPostProcessor(formatCode = true)).results.single()
}

I suppose, you can make a .jar of that module and write your own simple wrapper for JavaToKotlinConverter to make it work on files.


UPD: the code has migrated to the intellij-community repository, you can find relevant tests here: https://github.com/JetBrains/intellij-community/blob/2382372993bee233bc6fce95c3917a68a33da111/plugins/kotlin/j2k/new/tests/test/org/jetbrains/kotlin/nj2k/AbstractNewJavaToKotlinConverterSingleFileTest.kt

like image 114
hotkey Avatar answered Oct 22 '22 04:10

hotkey