Compile Java to Javascript


#1

Hi,

could the kotlin compiler be used to compile java-libraries directly to JavaScript?

Thanks


#2

No, the Kotlin compiler compiles Kotlin code, not Java code. However, there are other projects such as TeaVM which can be used to transpile Java libraries to JS.


#3

I know, but since kotlin is 100% java-compatible, what’s the downside of converting the code to kotlin and then compiling it to JS.


#4

Converting Java code to Kotlin is not a 100% automated process.

Also, I don’t see why this is a worthwhile approach at all; transpiling JVM bytecode to JS should be faster and more reliable.


#5

So can Kotlin generate JS for some dependent jars?

Let’s say in my library written in Kotlin i’m using Apache StringUtils that are obviously written in Java and compiled into JVM bytecode. Can Kotlin generate JS code for my library meaning it should generate JS meaing it should compile JS for compiled Apache StringUtils bytecode too?


#6

No, the Kotlin compiler cannot generate JS code from jar files. If you’re using Apache StringUtils in your project, you need to either replace it with a pure Kotlin implementation, or use the multiplatform project support to provide an alternative implementation for JS.


#7

Thanks for fast reply! Just to make it completely clear for me. I’m going to write Kotlin protobuf plugin similar to what [Apple wrote for Swift](https://github.com/apple/swift-protobuf/. Taking into account previous discussion i expect it to be helpful for those who targets multiplatform (let’s say require some protobuf objects to be used in Js). Is it correct?


#8

We’re working on an official serialization solution with support for protobuf already: https://github.com/kotlin/kotlinx.serialization


#9

Thanks for the link. But it seems to be orthogonal to what i’m saying. If i understood correctly kotlinx.serialization allows to serialize/deserialize Kotlin objects (using kotlinx.serialization annotations) to some representation (including protobuf). But it does not allow to generate Kotlin class definition (.kt) from protobuf (.proto) file. Is that correct?


#10

Yes, that’s correct; I misunderstood what you were going to do.


#11

Thanks for clarification