How to setup serialization in IntelliJ/Kotlin?

2020-05-06 05:17发布

问题:

My apologies for a noob question: I'm trying to check out how serialization works in Kotlin.

To this end, I created a Gradle project like this:

edited the generated build.gradle.ktsby adding just one line

plugins {
    java
    kotlin("jvm") version "1.3.71"
    id("org.jetbrains.kotlin.plugin.serialization") version "1.3.71"
}

group = "org.example"
version = "1.0-SNAPSHOT"

repositories {
    mavenCentral()
}

dependencies {
    implementation(kotlin("stdlib-jdk8"))
    testCompile("junit", "junit", "4.12")
}

configure<JavaPluginConvention> {
    sourceCompatibility = JavaVersion.VERSION_1_8
}
tasks {
    compileKotlin {
        kotlinOptions.jvmTarget = "1.8"
    }
    compileTestKotlin {
        kotlinOptions.jvmTarget = "1.8"
    }
}

and created this Kotlin source file:

import kotlinx.serialization.*
import kotlinx.serialization.json.*

@Serializable
data class Data(val a: Int, val b: String = "42")

But when I build this project, I get this error:

Unresolved reference: kotlinx

If I remove the first two offending lines, I get this error instead:

Cannot access 'Serializable': it is internal in 'kotlin.io'

What am I doing wrong here? (Also, do I need Gradle to use serialization in IntelliJ/Kotlin 1.3.71? )

回答1:

Finally, figured it out. A BUG in IntelliJ IDEA was foiling my troubleshooting.

Leaving the answer for anyone who might find this question via Google:

build.gradle.kt needs to be

plugins {
    java
    kotlin("jvm") version "1.3.71"
    kotlin("plugin.serialization") version "1.3.71"
}

repositories {
    // artifacts are published to JCenter
    jcenter()
}

dependencies {
    implementation(kotlin("stdlib", org.jetbrains.kotlin.config.KotlinCompilerVersion.VERSION))
    implementation("org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.20.0")
}

The official instructions have a buggy version of this: no org.jetbrains.kotlin.config.

However, this is not enough. I was executing "Run" from the Kotlin file. This leads to another error

error: unable to evaluate script, no scripting plugin loaded

due to a nasty bug (as in, I wasted HOURS and HOURS trying to figure out what I was doing wrong) https://youtrack.jetbrains.com/issue/KT-37814

One needs to explicitly execute "Build project".