https://kotlinlang.org logo
#scripting
Title
# scripting
s

starke

06/23/2022, 10:25 PM
I am trying to figure out how to import a class that is defined in a separate file. I found this discussion from a while ago, but wanted to check if there have been any updates related to this? I can access properties that are defined in
foo.main.kts
when I use
@file:Import
, but can’t figure out a way to access classes that are defined in
foo.main.kts
Copy code
@file:Import("foo.main.kts")
I tried referencing the class like
Foo_main.MyClass()
, but it doesn’t seem to work 🤔 Thanks in advance!
i

ilya.chernikov

06/24/2022, 3:43 PM
The situation is changed a bit with 1.7, please try it out. But it is not problem free unfortunately. Namely, accessing classes from imported scripts should work fine unless the used class does not capture anything from surrounding script. This is something we will address in the future, but for a moment, as a workaround, you can create a "constructor" function in the script that defines the class. E.g.: script1.main.kts
Copy code
val foo = 1
class Bar {
   val baz = foo + 1 // captures foo from the script
}
val x = Bar().baz // should work fine in the same script
fun makeBar() = Bar() // "constructor"
script2.main.kts
Copy code
@file:Import("script1.main.kts")

println(makeBar().baz) // works
println(Bar().baz) // fails
(I realized that the issue is not documented yet, so I created the YT ticket to follow - https://youtrack.jetbrains.com/issue/KT-52957/Scripting-capturing-classes-constructors-are-not-called-correctly-from-an-importing-script-and-probably-in-REPL-too)
s

starke

06/24/2022, 3:44 PM
will give that a try, thanks!
The IDE compiler doesn’t like it, but it does run successfully!
i

ilya.chernikov

06/24/2022, 4:02 PM
Good!. Import is not yet properly supported by the IntelliJ plugin.
👍 1
s

starke

06/24/2022, 4:24 PM
It also seems like I have to add the
@file:DependsOn
to both scripts even if only the script that is imported by the other is directly using the dependency. Is that a known/expected issue?
i

ilya.chernikov

06/24/2022, 5:08 PM
No, it is not expected, please file an issue in YT with some details.
👍 1
s

starke

06/27/2022, 5:09 PM
It might have been an error on my part - it’s working fine now 🙂
👍 1
3 Views