0
# Kotlin Scripting JSR-223
1
2
Kotlin Scripting JSR-223 provides a JSR-223 (Scripting for the Java Platform) compliant implementation for Kotlin, enabling Java applications to execute Kotlin scripts dynamically at runtime through the standard Java scripting API. This library implements the JSR-223 ScriptEngine interface to allow seamless integration of Kotlin scripting capabilities into Java applications.
3
4
## Package Information
5
6
- **Package Name**: kotlin-scripting-jsr223
7
- **Package Type**: maven
8
- **Language**: Kotlin
9
- **Installation**: Add to your build.gradle.kts or pom.xml:
10
11
**Gradle:**
12
```kotlin
13
dependencies {
14
implementation("org.jetbrains.kotlin:kotlin-scripting-jsr223:2.2.0")
15
}
16
```
17
18
**Maven:**
19
```xml
20
<dependency>
21
<groupId>org.jetbrains.kotlin</groupId>
22
<artifactId>kotlin-scripting-jsr223</artifactId>
23
<version>2.2.0</version>
24
</dependency>
25
```
26
27
## Core Imports
28
29
```kotlin
30
import kotlin.script.experimental.jsr223.KotlinJsr223DefaultScriptEngineFactory
31
import kotlin.script.experimental.jsr223.KotlinJsr223DefaultScript
32
import kotlin.script.experimental.jsr223.KOTLIN_JSR223_RESOLVE_FROM_CLASSLOADER_PROPERTY
33
```
34
35
For Java applications using JSR-223:
36
```java
37
import javax.script.ScriptEngineManager;
38
import javax.script.ScriptEngine;
39
import javax.script.Bindings;
40
```
41
42
## Basic Usage
43
44
### Using with JSR-223 ScriptEngineManager
45
46
```java
47
import javax.script.*;
48
49
// Get Kotlin script engine through JSR-223
50
ScriptEngineManager manager = new ScriptEngineManager();
51
ScriptEngine engine = manager.getEngineByExtension("kts");
52
53
// Execute simple Kotlin script
54
Object result = engine.eval("val x = 5 + 3; x");
55
System.out.println(result); // Output: 8
56
57
// Using bindings to pass data between Java and Kotlin
58
Bindings bindings = engine.createBindings();
59
bindings.put("name", "World");
60
bindings.put("count", 42);
61
62
Object greeting = engine.eval("\"Hello, $name! Count: $count\"", bindings);
63
System.out.println(greeting); // Output: Hello, World! Count: 42
64
```
65
66
### Direct Factory Usage
67
68
```kotlin
69
import kotlin.script.experimental.jsr223.KotlinJsr223DefaultScriptEngineFactory
70
71
val factory = KotlinJsr223DefaultScriptEngineFactory()
72
val engine = factory.scriptEngine
73
74
// Execute Kotlin script
75
val result = engine.eval("listOf(1, 2, 3).map { it * 2 }")
76
```
77
78
## Architecture
79
80
The library is built around several key components:
81
82
- **KotlinJsr223DefaultScriptEngineFactory**: Main factory implementing JSR-223 ScriptEngineFactory interface
83
- **KotlinJsr223DefaultScript**: Base script template providing JSR-223 bindings integration
84
- **Configuration Objects**: Default compilation and evaluation configurations for script execution
85
- **Dependency Resolution**: Automatic classpath detection and dependency management
86
- **Service Provider**: Automatic registration with JSR-223 ScriptEngineManager
87
88
## Capabilities
89
90
### Script Engine Factory
91
92
Main entry point for creating Kotlin script engines through JSR-223.
93
94
```kotlin { .api }
95
class KotlinJsr223DefaultScriptEngineFactory : KotlinJsr223JvmScriptEngineFactoryBase() {
96
override fun getScriptEngine(): ScriptEngine
97
}
98
```
99
100
The factory automatically configures dependency resolution from the current context classloader and provides caching for performance optimization.
101
102
### Script Template
103
104
Base template class for JSR-223 Kotlin scripts with integrated bindings support.
105
106
```kotlin { .api }
107
abstract class KotlinJsr223DefaultScript(val jsr223Bindings: Bindings) : ScriptTemplateWithBindings(jsr223Bindings) {
108
fun eval(script: String, newBindings: Bindings): Any?
109
fun eval(script: String): Any?
110
fun createBindings(): Bindings
111
}
112
```
113
114
**Usage Examples:**
115
116
```kotlin
117
// Inside a script context, access bindings
118
val userName = jsr223Bindings["userName"] as String
119
val result = "Hello, $userName!"
120
121
// Evaluate another script with custom bindings
122
val customBindings = createBindings()
123
customBindings["value"] = 100
124
val computation = eval("value * 2", customBindings)
125
126
// Evaluate with current bindings
127
val simpleResult = eval("42 + 8")
128
```
129
130
### Configuration Objects
131
132
Default configurations for script compilation and evaluation.
133
134
```kotlin { .api }
135
object KotlinJsr223DefaultScriptCompilationConfiguration : ScriptCompilationConfiguration
136
137
object KotlinJsr223DefaultScriptEvaluationConfiguration : ScriptEvaluationConfiguration
138
```
139
140
These objects provide:
141
- **Compilation Configuration**: Automatically imports all JSR-223 bindings, configures JVM target
142
- **Evaluation Configuration**: Refines configuration before evaluation using JSR-223 context
143
144
### Dependency Resolution Control
145
146
System property for controlling how dependencies are resolved.
147
148
```kotlin { .api }
149
const val KOTLIN_JSR223_RESOLVE_FROM_CLASSLOADER_PROPERTY: String =
150
"kotlin.jsr223.experimental.resolve.dependencies.from.context.classloader"
151
```
152
153
**Usage:**
154
155
```java
156
// Enable experimental direct classloader resolution
157
System.setProperty(
158
"kotlin.jsr223.experimental.resolve.dependencies.from.context.classloader",
159
"true"
160
);
161
162
// Create engine with experimental dependency resolution
163
ScriptEngine engine = new ScriptEngineManager().getEngineByExtension("kts");
164
```
165
166
When set to `"true"`, dependencies are resolved directly from the context classloader using reflection. Otherwise, the classpath is extracted first and used for dependency resolution.
167
168
## Error Handling
169
170
The library integrates with standard Java exception handling patterns:
171
172
```java
173
try {
174
Object result = engine.eval("invalid kotlin syntax }");
175
} catch (ScriptException e) {
176
System.err.println("Script compilation/execution error: " + e.getMessage());
177
}
178
```
179
180
## Advanced Usage
181
182
### Custom Bindings and Context Management
183
184
```java
185
ScriptEngine engine = new ScriptEngineManager().getEngineByExtension("kts");
186
187
// Create custom bindings
188
Bindings bindings = engine.createBindings();
189
bindings.put("dataList", Arrays.asList(1, 2, 3, 4, 5));
190
bindings.put("multiplier", 3);
191
192
// Execute script with access to Java objects
193
String script = """
194
val processedData = (dataList as List<Int>).map { it * multiplier }
195
processedData.joinToString(", ")
196
""";
197
198
Object result = engine.eval(script, bindings); // "3, 6, 9, 12, 15"
199
```
200
201
### Integration with Kotlin Libraries
202
203
Scripts can access the full Kotlin standard library and any dependencies available on the classpath:
204
205
```java
206
// Assuming kotlin-coroutines is on the classpath
207
String coroutineScript = """
208
import kotlinx.coroutines.*
209
210
runBlocking {
211
val deferred = async { delay(100); "Async result" }
212
deferred.await()
213
}
214
""";
215
216
Object asyncResult = engine.eval(coroutineScript);
217
```
218
219
## Service Provider Integration
220
221
The library automatically registers with JSR-223 through the service provider mechanism:
222
223
- **Service File**: `META-INF/services/javax.script.ScriptEngineFactory`
224
- **Implementation**: `kotlin.script.experimental.jsr223.KotlinJsr223DefaultScriptEngineFactory`
225
226
This enables automatic discovery by `ScriptEngineManager.getEngineByExtension("kts")` and `ScriptEngineManager.getEngineByName("kotlin")`.
227
228
## Types
229
230
```kotlin { .api }
231
// From javax.script package (JSR-223 standard)
232
interface ScriptEngine {
233
fun eval(script: String): Any?
234
fun eval(script: String, bindings: Bindings): Any?
235
fun createBindings(): Bindings
236
// ... other JSR-223 methods
237
}
238
239
interface Bindings : MutableMap<String, Any?> {
240
// Standard map operations for variable binding
241
}
242
243
interface ScriptEngineFactory {
244
fun getScriptEngine(): ScriptEngine
245
// ... other factory methods
246
}
247
248
// From Kotlin scripting API
249
abstract class ScriptTemplateWithBindings(val bindings: Bindings)
250
251
class ScriptCompilationConfiguration
252
class ScriptEvaluationConfiguration
253
```