How to compile and use Kotlin code in runtime?

This feels like an XY Problem. You want to know how to compile Kotlin on the fly so that you can more easily use Vert.x by running from Kotlin source files instead of compiled code. But really the recommended path for Vert.x usage is to create a simple bit of code that deploys your verticle within compiled code.

In the question, your link for language support says Vert.x 2 in the path "vertx.io/vertx2/language_support.html"; which is different than how it is now done in Vert.x 3. I think you are merging two thoughts into one. First that Vert.x 3 wants you to run Java/Kotlin files from source (it doesn't really; that was a Vert.x 2 thing they moved away from for compiled languages), and second that you need custom language support (you don't).

You should try to use Vert.x 3 by running compiled code. To do so, build your classes and run your own main() that deploys a verticle programatically. Your code would be simple as:

import io.vertx.core.Vertx

fun main(args: Array<String>) {
    val vertx = Vertx.vertx()
    vertx.deployVerticle(SomeVerticleOfMine())
}

Alternatively, the docs for running and deploying from the command-line say:

Vert.x will compile the Java source file on the fly before running it. This is really useful for quickly prototyping verticles and great for demos. No need to set-up a Maven or Gradle build first to get going!

And really it is indeed just for prototyping and quick testing, and it isn't any faster than letting your IDE do the same and running from the compiled classes. You also then have debugging features of the IDE which are infinitely valuable.

For a few helper libraries for using Kotlin with Vert.x, view these options:

  • Vert.x 3 module for Klutter - I am the author, one of my libraries
  • Vert.x 3 helpers for Kotlin - by Cy6erGn0m
  • Kovert, a REST framework for Vert.x 3 - I am the author, one of my libraries
  • Vert.x nubes - not Kotlin specific, but makes Vert.x-Web friendlier for JVM languages.

There is a full sample project of running Vert.x + Kovert (specifically start with the App class). You can look at the code of Kovert to do your own similar work of starting and running Vert.x nicely, with Promises or however you wish. The docs for Kovert have links to code for starting Vertx and also starting a Verticle to use Vert.x-Web, so more sample code you can read. But it helps to understand Injekt (light-weight dependency registry), Kovenant (promises library), and Klutter configuration injection to understand the complete sample.

Other quick note, Vert.x has codegen support for other languages, but since you can call all of the Java version directly, it does not need to support Kotlin either.


Kotlin 1.1 comes with javax.script (JSR-223) support, which means you can use it as scripting engine similarly to JavaScript with Nashorn.

Tags:

Kotlin

Vert.X