Pass parameters into the Kotlin Script

Hello,

Do you know, how is better to pass parameter (in general case - class instance) to the Kotlin Script?

I have script, which defines internally Map<String, ()->SomeResult>.

I’d like to have an ability to run string script with parameter to execute the target function from map.

What I tried:

  1. Put custom object into the scripting context. And looks like Kotlin Scripting engine changes class names, so I’m unable to find the generated class via reflection by name.
  2. I tried also to create the interface and next put the generated class into the script. Next I thank that class can be found by looking up all classes from the ClassLoader (it is single who implements the target interface). However, looks like because of JVM optimisations, that class wasn’t loaded into memory, so lookup was failed.
  3. I tried to add my code into the top of script, however import statements should be upper than any code, so this idea was failed.
  4. My script should return the result, so I couldn’t add code into the end of file.

So, does anybody know, how can I pass parameter to the Kotlin Script?

It should be possible to do via providedProperties key, but I never did that.

You can put your argument inside of implicit receiver like it is done here or here.

2 Likes

I tried that. In general case, this schema doesn’t work (I think I’ll create ticket in Kotlin YouTrack later).

For instance, compiler adds additional code for the script below in the top of file (it is looks like that). Therefore, code isn’t able to compile, because imports should be in the top of file:

import kotlin.collections.* // it isn't needed, just example how to break compilation with implicit receivers

1+2

I do not have time right not to check, but you are welcome to ask in slack channel in #scripting. They respond quickly.

1 Like