Compile Kotlin code from string at runtime


#1

Hey,
I wanted to ask if it’s possible to compile Kotlin code if it’s represented as a String.
This should happen at runtime in a JUnit test.
Suppose I have a test code snippet and I just want to check whether it’s valid Kotlin code or not.
Is there any build-in mechanism to do this?

In Java this is possible with the following code by getting the Java compiler from the ToolProvider and compile a file for instance.

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
compiler.run(null, null, null, javaFile.getAbsolutePath());

#2

Its no updated with 1.3.0 but here is an example: https://gist.github.com/oshai/9dc447166dc792b8c95fa804dc696551


#3

I do not think it is a good way to do so.

Kotlin supports JSR223 scripting and there is an example in the official repository.

Also there is new scripting support via KEEP-75 in 1.3, but I am not sure it is fully functional yet.


#4

Yes, it is not exactly clear from the question what is the use case. JSR might be a good option


#5

Thanks for your help. That seems very promising.
My use case is that I have a JUnit test like this. I need to check if my Kotlin code generator generates valid Kotlin code. To acccomplish that I wanted to compile and thus verify it with the help of the Kotlin compiler.
I have something in mind which comes close to the following example. What would you recommend to use in my case?

@Test fun lintClassName() {
  val generatedCode = api.generateCode()
  val successful = KotlinCompiler.compile(generatedCode)
  assertThat(successful).isTrue
}

#6

The JSR approach with eval is simpler and looks like it will fit your needs. I haven’t used it but take a look at the examples above.