Using Java enums in Kotlin


#1

Hi!

I would like to use some enums already existing in a Java-module (spread out in different packages) in my Kotlin-JS module. Is it possible to some way generate a Kotlin class from a Java-class? I’m thinking of making my self a “script” that generates those enums.

Any guidance or ideas to best solve this is appreciated.

Thanks!

Jørund


#2

If you want to convert java to kotlin you can use konlin converter in your idea. But i am not sure that such a conversion will help you in your case. Because in most cases converted class will have a lot of a dependencies. So you will have to convert all of them. I suggest you to look for a js equivalents.


#3

But lets say the enums are without dependencies. Would it then be possible to export (generate) one Java enum to a Kotlin enum?


#4

Yep. Why don’t you try it yourself?


#5

The converter does not “export” anything; it will delete the original Java file and replace with with a Kotlin file. You can’t have multiple versions of the same declaration (with the same qualified name) in a single project.


#6

I wonder if you guys misunderstand me. I don’t want to manually export a Java class to Kotlin. However programatically (issued by a maven code generation plugin) generate a Kotlin class (enum) from a Java class (enum). The generated Kotlin-class will not reside as source code but in target under generated-classes. The package of the generated class will not be the same package as the Java-class.

Is this possible?


#7

There is no such plugin at this time. Why don’t you simply convert the Java enums to Kotlin? It will be far easier.


#8

Thanks for the follow up. Sounds like a good idea :slight_smile:

Can I mix Kotlin and Java one in the source dir in the same module? Must I have separate source dirs? Like src/main/java and src/main/kotlin?


#9

Yes, you can mix Kotlin and Java in the same directory.


#10

Great! Thanks!