I am trying to figure out how to import a class th...
# scripting
s
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
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
will give that a try, thanks!
The IDE compiler doesn’t like it, but it does run successfully!
i
Good!. Import is not yet properly supported by the IntelliJ plugin.
👍 1
s
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
No, it is not expected, please file an issue in YT with some details.
👍 1
s
It might have been an error on my part - it’s working fine now 🙂
👍 1