intellij-ideakotlinscratch-filesealed-class

How can I configure the Kotlin version used for scratch files in IntelliJ IDEA?


I've recently installed IntelliJ IDEA in an attempt to learn Kotlin. I've set up a Kotlin project and configured IDEA to use the latest stable release of the Kotlin plugin (1.2.71-release-IJ2018.2-1).

The following code works fine if executed in a project file (e.g. src/main.kt):

sealed class Port
class InputPort<in T> : Port()
class OutputPort<out T> : Port()

However, if I try to execute this in a scratch file instead, I get these errors:

scratch.kts:2:25: error: cannot access '<init>': it is private in 'Port'
class InputPort<in T> : Port()
                        ^
scratch.kts:2:25: error: this type is sealed, so it can be inherited by only its own nested classes or objects
class InputPort<in T> : Port()
                        ^
scratch.kts:3:27: error: cannot access '<init>': it is private in 'Port'
class OutputPort<out T> : Port()
                          ^
scratch.kts:3:27: error: this type is sealed, so it can be inherited by only its own nested classes or objects
class OutputPort<out T> : Port()
                          ^

From the Kotlin documentation, I can see that this is because this usage of sealed classes is only valid in Kotlin 1.1+. This implies that the project files are being executed with >= Kotlin 1.1, whereas scratch files are using < Kotlin 1.1.

What I'm wondering is why Kotlin scratch files don't appear to use the same version of Kotlin as the main project files do, and how I can specify the Kotlin version to use for executing the scratch files.

Below is an example of a run/debug configuration I use for my scratch files:

When executing the scratch file, I see the following command appear in the scratch output pane (formatting altered for clarity):

"C:\Program Files\Java\jdk-11\bin\java.exe" ^
    -javaagent:C:\Users\<me>\AppData\Local\JetBrains\Toolbox\apps\IDEA-C\ch-0\182.4505.22\lib\idea_rt.jar=53595:C:\Users\<me>\AppData\Local\JetBrains\Toolbox\apps\IDEA-C\ch-0\182.4505.22\bin ^
    -Dfile.encoding=windows-1252 ^
    -classpath C:\Users\<me>\.IdeaIC2018.2\config\plugins\Kotlin\kotlinc\lib\kotlin-compiler.jar;C:\Users\<me>\.IdeaIC2018.2\config\plugins\Kotlin\kotlinc\lib\kotlin-reflect.jar;C:\Users\<me>\.IdeaIC2018.2\config\plugins\Kotlin\kotlinc\lib\kotlin-stdlib.jar;C:\Users\<me>\.IdeaIC2018.2\config\plugins\Kotlin\kotlinc\lib\kotlin-script-runtime.jar org.jetbrains.kotlin.cli.jvm.K2JVMCompiler ^
    -kotlin-home C:\Users\<me>\.IdeaIC2018.2\config\plugins\Kotlin\kotlinc 
    -script C:/Users/<me>/.IdeaIC2018.2/config/scratches/scratch_2.kts

Solution

  • It isn't a problem with your configuration. Currently sealed class can be inherited only by its own nested class in Kotlin scripts.

    There is an issue in YouTrack: https://youtrack.jetbrains.com/issue/KT-20180