Hi folks, the Kotlin Main Kts supports Kotlinx.ser...
# scripting
s
Hi folks, the Kotlin Main Kts supports Kotlinx.serialization ? if so, there is any example of using it?
m
I don't think there is since it requires a plugin. I'm using moshi instead.
☝️ 1
Maybe you can make
kotlinx-serialization
work using only the runtime. I guess there's a Json parser there
I got curious so made a small test, looks like it is working:
Copy code
@file:DependsOn("org.jetbrains.kotlinx:kotlinx-serialization-json-jvm:1.0.1")

import kotlinx.serialization.json.*


val jsonObject = JsonObject(
    mapOf(
        "int" to JsonPrimitive(0),
        "double" to JsonPrimitive(0.5),
        "string" to JsonPrimitive("String"),
        "bool" to JsonPrimitive(true),
        "list" to JsonArray(
            listOf(
                JsonPrimitive(0),
                JsonPrimitive(1),
                JsonPrimitive(2),
                JsonPrimitive(3)
            )
        ),
        "object" to JsonObject(
            mapOf("key" to JsonPrimitive("value")
            )
        )
    )
)


println(Json.parseToJsonElement(jsonObject.toString()))
i
Since 1.4.20 you can use plugins with
main-kts
, in particular with
kotlinx.serialization
, see, e.g., the test here - https://github.com/JetBrains/kotlin/blob/master/libraries/tools/kotlin-main-kts-test/test/org/jetbrains/kotlin/mainKts/test/mainKtsIT.kt#L94
👍 2
m
Nice! Can the plugin be added from the
*.main.kts
file itself ? Or does it always need the
-Xplugin
parameter?
(and where can I find the plugin path if
-Xplugin
is mandatory?)
i
No, unfortunately you need to configure plugin via the
-Xplugin
parameter to the
kotlinc
. (or you can write a custom host/runner that includes the plugin by default.) The plugin is installed along with kotlin CLI compiler, to the
$KOTLIN_HOME/lib/
.
👍 1
m
So... I just tried and it seems to work without specifying
-Xplugin
? 🤔
Copy code
martin@MacBook:~/dev/kotlinc$ kotlinc -script serialization.main.kts  
{"firstName":"James","lastName":"Bond"}
User(firstName=James, lastName=Bond)
Which is a good thing I guess? Just wondering if I'm missing something there
Now the only thing missing is IDE support 😇
i
I don't know, why it works. Maybe it was enabled by default at some point, but I cannot find any traces of it so far. I'll check with the serialization authors a bit later. IDE support for advanced scripting features is lagging behind, unfortunately. Cannot cover everything.
🙏 1
💯 1
m
Interestingly, this was working because I was experimenting with shebang magic and I had
#!$KOTLIN_HOME/bin/kotlinc -Xplugin=$KOTLIN_HOME
at the start of my file...
Note that despite having the shebang, I was still calling
kotlinc -script serialization.main.kts
manually
So that would hint at kotlinc somehow reading the shebang line?
p
I'm also missing a convenient way to use some of the Gradle plugins, see: https://youtrack.jetbrains.com/issue/KT-47384