# How to Compile Kotlin Code at Runtime from Java?

**URL:** <https://discuss.kotlinlang.org/t/how-to-compile-kotlin-code-at-runtime-from-java/30324>\
**Category:** Uncategorized\
**Created:** [May 5, 2025, 1:09pm UTC](https://discuss.kotlinlang.org/t/how-to-compile-kotlin-code-at-runtime-from-java/30324 "2025-05-05T13:09:07Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![semenov.valentine](https://avatars.discourse-cdn.com/v4/letter/s/a8b319/32.png) [@semenov.valentine](https://discuss.kotlinlang.org/u/semenov.valentine)\
**Post date:** [May 5, 2025, 1:09pm UTC](https://discuss.kotlinlang.org/t/how-to-compile-kotlin-code-at-runtime-from-java/30324/1 "2025-05-05T13:09:07Z")

</div>

Hey,  
I have a task where I need to compile Kotlin source code at runtime from within a Java application. Is kotlin-compiler-embeddable the recommended way to achieve this?

For now, I am using K2JVMCompiler, but I’m not sure if this is the best and most stable way. Is this the right tool for compiling Kotlin code from Java at runtime, or are there better alternatives or best practices I should consider?

---

<div class="post-metadata">

**Author:** ![vk](https://avatars.discourse-cdn.com/v4/letter/v/cab0a1/32.png) [@vk](https://discuss.kotlinlang.org/u/vk)\
**Post date:** [May 7, 2025, 1:40pm UTC](https://discuss.kotlinlang.org/t/how-to-compile-kotlin-code-at-runtime-from-java/30324/2 "2025-05-07T13:40:18Z")

</div>

Depending on the nature of your task one of possible solutions would be to compile that kotlin code into javascript and then ‘plug’ that compiled javascript into jvm via javascript engine ( _Nashorn_ etc.)

---

<div class="post-metadata">

**Author:** ![John\_Fairhall](https://avatars.discourse-cdn.com/v4/letter/j/e36b37/32.png) [@John\_Fairhall](https://discuss.kotlinlang.org/u/John_Fairhall)\
**Post date:** [September 2, 2025, 12:05am UTC](https://discuss.kotlinlang.org/t/how-to-compile-kotlin-code-at-runtime-from-java/30324/3 "2025-09-02T00:05:23Z")

</div>

Hi Semenov,

I am trying to do the same thing, but I have been getting an error on compilation ( [Error when compiling with K2JVMCompiler dynamically in Java](https://discuss.kotlinlang.org/t/error-when-compiling-with-k2jvmcompiler-dynamically-in-java/30744) )

Did you have this problem?
