https://kotlinlang.org logo
Join Slack
Powered by
# scripting
  • e

    Eugen Martynov

    11/04/2024, 11:53 AM
    Hey hey, I'm tying to run kotlin script on CI and it is corporate envirnement that requires some JDK certificate patching. I see that it fails with 502 when trying to download the dependency. How can I troubleshot it? What could be the reason? How kotlin script resolves the maven dependency?
    p
    • 2
    • 1
  • w

    WayZer

    11/10/2024, 1:43 PM
    Is it bug or by design: The script can't access
    protected
    in base class with new scripting version(KT 2.0+ library) Workaround `@Suppress("INVISIBLE_REFERENCE")`: works when compile and runtime.
    p
    • 2
    • 5
  • j

    Jason

    11/14/2024, 11:31 PM
    Has anyone ran into issues with the Repository annotation, MavenDependencyResolver, Aether and dependencies declaring a greater than version (1.2.+)? I noticed that when the underlying Aether parts I modify the collected dependencies I can fix my issue by using the debugger to fix the version (i.e. 1.2.0). Curious if Aether can be configured to match this semantic versioning pattern?
    p
    • 2
    • 1
  • m

    mbonnin

    11/20/2024, 3:30 PM
    My 2 cents but I believe https://blog.jetbrains.com/kotlin/2024/11/state-of-kotlin-scripting-2024/ may hurt Kotlin scripting more than it's helping. In this tldr; era, the post sounds like a deprecation notice while it's actually quite the opposite? It's about focusing the scripting effort where it matters most?
    💯 3
    p
    e
    +4
    • 7
    • 24
  • s

    spierce7

    11/21/2024, 4:01 PM
    I saw the blog post about kotlin scripting, and was curious what it's impacts are. It's future seems far more vague than before. i.e. I was planning on using Kotlin-playground for an internal project, which I know uses kotlin scripting. Is the kotlin-playground use case of Kotlin scripting dead, or alive?
    e
    • 2
    • 2
  • y

    yostane

    12/05/2024, 4:20 PM
    Hello. I've been using JBang (a tool that got inspiration from kscript) to do the advent of code. You can take a look here to see what it looks like: https://github.com/yostane/adventofcode/tree/main/2024
    👍 1
  • i

    István Mészáros

    12/06/2024, 9:21 AM
    Should IDEA with K2 mode enabled load custom script definitions from imported Gradle projects? It used to work in the past but doesn't work now, not sure when it broke. 🙂 I have a Gradle project with the definition class and the appropriate marker file in META-INF. The IDEA log only loads the Gradle DSL definitions, no error or any mention of my custom script type.
    👀 1
    e
    • 2
    • 1
  • n

    Nino

    12/16/2024, 12:32 PM
    Hello, today I wanted to write a script in Kotlin, but I'm completely lost. Maybe you could give me some guidance. • I'm an Android dev using Android Studio • I want to write a script to move / rename files in a folder. Nothing fancy but I would like to avoid using bash and use Kotlin instead. • The resulting "script" should be usable easily by the other team members or the CI machine, in Windows or Mac. • The resulting "script" should be readable and modifiable by other devs (and not the compiled .jar) So I tried: • https://umang91.medium.com/scripting-in-kotlin-eaf01750bbee which was soooo promising but I see the
    kotlin
    CLI is already dead ? Such a same it seemed such a beautiful and powerful replacement for bash files 😞 • Then I tried Kotlin Notebook but they never mentionned that it needed Intellij Ultimate. I lost half a day trying to download the plugin until I understood. Greedy fuckers 😞 • Then I tried
    ki shell
    but I don't quite understand what is it for. Looks like Kotlin Playground locally, which doesn't fit my need. • Then I'm trying to use
    kotlinc -script
    but there's no documentation (https://kotlinlang.org/docs/command-line.html#run-scripts), or I don't understand the relation between the overly complex documentation linked there (https://kotlinlang.org/docs/custom-script-deps-tutorial.html) and a simple CLI-invoked script in Kotlin. Please guide me in this maze I'm already on the verge to going back to bash scripting. What tool would you use to produce the specified script ?
    p
    v
    • 3
    • 44
  • p

    Piotr Krzemiński

    01/24/2025, 6:00 PM
    I want to compile Kotlin scripts within a Kotlin script 😄 just compile, to validate if they compile fine or with a particular error message. So far I'm getting:
    Copy code
    e: java.lang.ExceptionInInitializerError
    ...
    Caused by: java.lang.ClassCastException: class org.jetbrains.kotlin.idea.KotlinFileType cannot be cast to class org.jetbrains.kotlin.com.intellij.openapi.fileTypes.LanguageFileType (org.jetbrains.kotlin.idea.KotlinFileType and org.jetbrains.kotlin.com.intellij.openapi.fileTypes.LanguageFileType are in unnamed module of loader java.net.URLClassLoader @5d5c04f9
    ...
    my code in the thread
    ♾️ 1
    v
    • 2
    • 9
  • p

    Piotr Krzemiński

    01/27/2025, 3:28 PM
    a pleasant surprise - to consume a KMP library from a script, I didn't have to add
    -jvm
    - just
    @file:DependsOn("it.krzeminski:snakeyaml-engine-kmp:3.1.0")
    works now 🙂
    mind blown 2
    nono 2
    🤔 1
    m
    j
    +2
    • 5
    • 42
  • r

    ribesg

    02/19/2025, 2:11 PM
    How do you make IntelliJ recognize a
    .main.kts
    file as a Kotlin Script and provide highlighting, completion and everything else? I just have a folder containing my scripts for now and it just treats them as plain text
    p
    m
    +2
    • 5
    • 36
  • o

    Olaf Gottschalk

    02/20/2025, 9:29 AM
    Hello Scripters! With moving my own DSL project to Kotlin 2.1 (coming from 1.9), I experience some problems with the tooling setup, specifically with IntelliJ offering syntax highlight and code completion on my own script files with their own extension. It used to work like this: In my DSL library project, there is a class with a
    @KotlinScript
    annotation like this:
    Copy code
    const val TRALA_FILE_EXTENSION = "trala.kts"
    
    @KotlinScript(
        displayName = "TraLa Script",
        fileExtension = TRALA_FILE_EXTENSION,
        compilationConfiguration = TraLaScriptConfiguration::class
    )
    abstract class TraLaScript
    plus, there is a resource file at this location:
    resources/META-INF/kotlin/script/templates/com.bmw.transformation.scripting.TraLaScript
    (which is empty) The compilation configuration looks like this:
    Copy code
    @Suppress("JavaIoSerializableObjectMustHaveReadResolve")
    object TraLaScriptConfiguration : ScriptCompilationConfiguration(
        {
            defaultImports(traLaDefaultImports)
    
            ide {
                acceptedLocations(ScriptAcceptedLocation.Everywhere)
            }
    
            jvm {
                jvmTarget("17")
                compilerOptions("-Xcontext-receivers")
            }
        }
    )
    The idea is that any project that uses my DSL library can have files anywhere (see
    acceptedLocations
    with the extension
    .trala.kts
    and the editor will offer syntax highlight and code completion / inspection. This used to work. Sometimes I had to restart IntelliJ... it was never straight forward. But it worked. Now, I cannot see any way to make the editor behave like I want. And I do not know what changed. In projects that DEPEND on my lib (with this setup), nothing works any more. In my library project itself, the default imports don't seem to work anymore! When I add a new file
    foo.trala.kts
    and start typing code, it inserts import statements that it should not, because they are part of the default imports... What am I doing wrong here? Is there any good documentation on these matters? Thanks! Olaf
    👀 1
    i
    v
    • 3
    • 67
  • p

    Piotr Krzemiński

    02/20/2025, 1:00 PM
    is there a remote chance to use Gradle Version Catalog with
    @file:DependsOn("...")
    ? 🙈 scripting would have to know where to look for the TOML file, and it's non-trivial to infer. It could traverse starting from the script's location, up the file tree, until it finds
    gradle/libs.versions.toml
    m
    v
    a
    • 4
    • 38
  • p

    Piotr Krzemiński

    02/20/2025, 3:06 PM
    I need help untangling what's wrong with fix(deps): update ktor monorepo to v3.1.0. Calling
    .github/workflows/end-to-end-tests.main.kts
    here: https://github.com/typesafegithub/github-workflows-kt/actions/runs/13436465865/job/37545104505?pr=1830 causes:
    java.lang.NoClassDefFoundError: kotlinx/io/unsafe/UnsafeBufferOperations
    . So far I checked that: • I cannot reproduce it locally (purged all caches, used Java 11) - reproduced it by setting a GitHub token, only then the problematic code path is executed • if I remove
    @file:DependsOn("io.github.typesafegithub:action-updates-checker:3.2.1-SNAPSHOT")
    and any pieces that depend on functions from it, it works - so this package is to blame •
    UnsafeBufferOperations
    was introduced in kotlinx-io 0.5.0 • ktor started using kotlinx-io starting 3.1.0 in this commit Something must still depend on kotlinx-io older than 0.5.0, but I cannot pin it down...
    ✅ 1
    v
    • 2
    • 20
  • r

    Rob Elliot

    02/28/2025, 1:20 PM
    Hi - is it possible in
    ScriptCompilationConfiguration
    to require a specific return type for the script? So that the script will fail to compile if the last expression is not of that type?
    i
    • 2
    • 1
  • w

    WayZer

    03/29/2025, 2:50 PM
    Just try scripting K2 with 2.1.20, still some bug. Script like this
    Copy code
    object TableVersion : IdTable<String>("TableVersion") {
        // can't use `text` as h2db don't support for primaryKey
        override val id: Column<EntityID<String>> = varchar("table", 64).entityId()
        override val primaryKey: PrimaryKey = PrimaryKey(id) // h2database#2191
        //...
    }
    will complain
    PrimaryKey
    class (inner class of Table) is not found. This example works with
    -language-version=1.9
    i
    • 2
    • 1
  • z

    zt

    04/04/2025, 4:12 AM
    I'm trying to get IntelliJ IDEA to recognize my custom script but it just refuses to do it. I've created an empty file at
    META-INF/kotlin/script/templates/dev.zt64.composables.ComposableScript
    but when I select the script nothing is resolved and the classpath is missing dependencies. I've tried adding
    isStandalone(false)
    to my compilation configuration as well here is the repository https://github.com/zt64/compose-scripts
    👀 1
  • o

    Olaf Gottschalk

    04/25/2025, 5:41 AM
    I found another very interesting quirk that I cannot explain to myself... How can it be that there is a difference in what the Kotlin compiler does when comparing internal IntelliJ / Gradle compilation with script compilation? I had this function definition in my internal scripting language:
    Copy code
    @TransformationDsl
        infix fun <D : Any, VO> SetOperation<S, D>.by(valueMapper: ValueMapper<Any?, VO>) =
            apply { source = source.map(valueMapper) }
    When this function is used in "normal IntelliJ" contexts, a call like this compiles and works just fine:
    Copy code
    set optional "overallWeightTransportation" from "GrossWeightTransportationQuantity" by unitCodeMapper
    If you look very closely to my generics, the generic type
    VO
    is not really relevant to this function, it has not bounds, the usage of the parameter
    valueMapper
    when passed to the
    map
    function does not care about this generic type, as
    map
    accepts everything. I did not realize this was over-engineered until when compiled with the script compiler I got this error:
    Copy code
    set optional "overallWeightTransportation" from "GrossWeightTransportationQuantity" by unitCodeMapper //later mandatory
                                                                                        ^^ Cannot infer type for this parameter. Specify it explicitly.
                                                                                        ^^ Not enough information to infer type argument for 'VO'.
    The key question is now: why does it work just fine in IntelliJ, but not in scripting compilation? Solution for my immediate problem was to replace
    VO
    with
    *
    of course... but the question remains... ;-)
    c
    • 2
    • 2
  • l

    louiscad

    05/05/2025, 12:34 AM
    Showing the intermediate values in scratch files is a wonderful idea!
    💯 5
    g
    v
    • 3
    • 4
  • r

    ritesh

    05/09/2025, 3:11 PM
    Wanted to get a sense of people if they are using k-script in CI and if there had been any gotchas or pain-points as compared to shell scripting or python-scripting, when to comes to debugging and other factors.
    v
    c
    • 3
    • 8
  • d

    Daniel Pitts

    05/10/2025, 4:41 PM
    Is it possible to use Kotlin Scripting as a way to allow extending a C++ program? For example, if I were to create a game engine in C++, and wanted to enable Kotlin scripting, would there be an easy way to do that?
    e
    m
    j
    • 4
    • 8
  • r

    Rob Elliot

    05/24/2025, 7:36 PM
    Apologies for the cross post, but perhaps people here have more experience of this?
    👀 1
    v
    l
    v
    • 4
    • 10
  • a

    AndrewStone

    06/27/2025, 8:56 PM
    Running a kotlin Jsr223 script engine, can the "host" programatically loop through all the global symbols inside the ScriptEngine?
  • d

    darkmoon_uk

    06/29/2025, 1:17 AM
    I really enjoy being able to write
    .kts
    scripts instead of `.sh`; keeping more complex scripts in a powerful, familiar language. Unfortunately the usefulness of
    kts
    is unduly limited by IntelliJ IDE's failure to resolve symbols across
    @file:Import
    dependencies - this is an essential feature for composing scripts together e.g. importing some library functions from a
    common.kts
    - meanwhile the scripts still run fine, it's just IDE support that's lacking. This problem has only become more impactful with junie Junie; as the agent sees 'unresolved' false positives and erroneously act upon them, struggling for a fix that never comes. kodee sad This limitation is very sad, given it's been hanging for over 2 years... KTIJ-16352 Scripts / IDE: unresolved reference when trying to import file in main.kts scripts with @Import annotation Any insights into this issue in or outside of JB? Is scripting just abandoned beyond what's needed for Gradle? Such a shame, it's a killer feature in my book.
    ⭐ 1
    plus one 1
    👍 8
    👍🏾 2
    m
    p
    v
    • 4
    • 32
  • s

    Stylianos Gakis

    07/04/2025, 2:35 PM
    Trying to give a shot to kotlin scripting for GH actions and I am stumped on this issue: I want to do something as simple as write something to GH env variables. Not using kotlin scripting I can do
    Copy code
    - name: This works
      run: echo SOME_VAR=asd >> $GITHUB_ENV
    - name: Using it
      run: echo $SOME_VAR
      env:
        SOME_VAR: ${{ env.SOME_VAR }}
    And this works perfectly fine. In Kotlin I try to do:
    Copy code
    runCommand("echo SOME_VAR=asd >> \$GITHUB_ENV")
    (where runCommand comes from here https://github.com/apollographql/apollo-kotlin/blob/65dd7a44a74ed016988777521248da164de32ea0/scripts/bump-kotlin-nightlies.main.kts#L71C1-L85C2 basically using
    ProcessBuilder
    ) And then I try to do the same exact
    Using it
    task, but nothing at all gets printed. The contents of
    SOME_VAR
    are just empty. Is this some issue with ProcessBuilder, or something I am doing which is wrong here?e
    m
    e
    p
    • 4
    • 12
  • m

    mbonnin

    07/27/2025, 2:58 PM
    Is there a way to debug what's happening when I click "synchronize" in a
    *.main.kts
    file? Like output or something? It won't import my dependencies but I'm unsure why...
    d
    • 2
    • 5
  • j

    joseph_ivie

    07/28/2025, 3:27 PM
    Someone mentioned this to me earlier: Is it possible to use KotlinX serialization in a
    *.main.kts
    ? It would be incredibly useful.
    e
    v
    • 3
    • 2
  • o

    Olaf Gottschalk

    08/01/2025, 5:10 AM
    When using the
    BasicScriptingHost.eval(...)
    function to run script code, is there any way, a script can programmatically add elements to the
    reports
    property of the
    ResultWithDiagnostics
    that it returns? In some situations that are caught at runtime of my script, I want to return a warning just like a compiler warning, but my script can only detect this at runtime like when a user does something they are not intended to do. My current "solution" is to log a warning using a logger... but this is really not what I want. I need this information as a side-information along with the result of the script evaluation. So, ideally, in my script, I would like to call a function that adds elements to this collection of
    ScriptDiagnostic
    elements with a severity of warning... Is that possible?
    i
    • 2
    • 2
  • t

    Tim Putnam

    08/05/2025, 8:30 PM
    I'm using kotlin 2.2.0, with
    BasicJvmScriptingHost
    embedded in an application that's dynamically loading JPMS modules using
    ModuleLayer
    . I simply want the classloader from this
    ModuleLayer
    to be visible to the compiler. I"m setting
    baseClassLoader
    in the host configuration thus:
    Copy code
    val hostconf = ScriptingHostConfiguration {
            jvm {
                baseClassLoader(appClassloader)
            }
        }
    I've also tried a variety of ways to set the classloader in the
    ScriptCompilationConfiguration
    but to no avail. I don't want to add explicit jars (e.g.
    dependenciesFromClassloader()
    ). I just want it to use a provided classloader, but it always just uses the main/boot classloader. This is something I've had working at some stage in the pass, but now doesn't seem to. I feel like I'm missing something obvious - it seems to want external files? Please, any pointers?
    m
    • 2
    • 2
  • d

    darkmoon_uk

    08/23/2025, 12:02 AM
    kodee loving Using a GitHub Actions pipeline? Consider using
    .kts
    files instead of Bash, to perform more complex steps; like preparing ECS Deployment tasks. The good news is - GitHub Actions images already include
    kotlin
    , so no complex preparation steps, just
    run: kotlin myScript.main.kts
    and off you go! kodee happy
    👍 4
    🎉 3
    👍🏾 1
    🙌🏼 1
    e
    n
    • 3
    • 3