0
# Script Templates
1
2
Script templates provide structured environments for Kotlin script execution with predefined parameter passing mechanisms and integration patterns. The kotlin-script-util library includes templates for JSR-223 integration and local file resolution.
3
4
## JSR-223 Templates
5
6
### KotlinStandardJsr223ScriptTemplate
7
8
Standard JSR-223 script template that provides bindings integration and nested script evaluation capabilities.
9
10
```kotlin { .api }
11
@ScriptTemplateDefinition
12
abstract class KotlinStandardJsr223ScriptTemplate(
13
val jsr223Bindings: Bindings
14
) : ScriptTemplateWithBindings {
15
16
fun eval(script: String, newBindings: Bindings): Any?
17
fun eval(script: String): Any?
18
fun createBindings(): Bindings
19
}
20
```
21
22
**Usage Example:**
23
24
```kotlin
25
import org.jetbrains.kotlin.script.jsr223.KotlinStandardJsr223ScriptTemplate
26
import javax.script.SimpleBindings
27
28
// This template is typically used internally by script engines
29
// Scripts extending this template can access jsr223Bindings and eval methods
30
31
// In a script that extends KotlinStandardJsr223ScriptTemplate:
32
val currentBindings = jsr223Bindings
33
val nestedResult = eval("2 + 3") // Evaluate nested script
34
val customBindings = createBindings()
35
customBindings["x"] = 10
36
val result = eval("x * 2", customBindings) // Result: 20
37
```
38
39
### Methods
40
41
#### eval(script: String, newBindings: Bindings): Any?
42
43
Evaluates a Kotlin script string with custom bindings.
44
45
**Parameters:**
46
- `script: String` - The Kotlin code to execute
47
- `newBindings: Bindings` - Custom variable bindings for the script
48
49
**Returns:** The result of script execution, or null for Unit results
50
51
**Example:**
52
53
```kotlin
54
val bindings = createBindings()
55
bindings["name"] = "Alice"
56
bindings["age"] = 30
57
58
val result = eval("""
59
"Hello, ${'$'}name! You are ${'$'}age years old."
60
""".trimIndent(), bindings)
61
62
println(result) // "Hello, Alice! You are 30 years old."
63
```
64
65
#### eval(script: String): Any?
66
67
Evaluates a Kotlin script string using the template's default bindings.
68
69
**Parameters:**
70
- `script: String` - The Kotlin code to execute
71
72
**Returns:** The result of script execution, or null for Unit results
73
74
**Example:**
75
76
```kotlin
77
// Assuming jsr223Bindings contains "count" -> 5
78
val result = eval("count * count")
79
println(result) // 25
80
```
81
82
#### createBindings(): Bindings
83
84
Creates a new empty bindings object for use with script evaluation.
85
86
**Returns:** A new Bindings instance
87
88
**Example:**
89
90
```kotlin
91
val newBindings = createBindings()
92
newBindings["data"] = listOf(1, 2, 3, 4, 5)
93
val sum = eval("data.sum()", newBindings)
94
println(sum) // 15
95
```
96
97
## Local File Resolution Templates
98
99
### StandardArgsScriptTemplateWithLocalResolving
100
101
Script template that provides command-line style arguments and automatic local file dependency resolution.
102
103
```kotlin { .api }
104
@ScriptTemplateDefinition(
105
resolver = LocalFilesResolver::class,
106
scriptFilePattern = ".*\\.kts"
107
)
108
abstract class StandardArgsScriptTemplateWithLocalResolving(
109
val args: Array<String>
110
)
111
```
112
113
**Usage Example:**
114
115
Scripts using this template can access command-line arguments and resolve local dependencies:
116
117
```kotlin
118
// In a .kts script file
119
@file:DependsOn("./lib/my-library.jar")
120
121
// Access command-line arguments
122
println("Script started with ${args.size} arguments")
123
args.forEachIndexed { index, arg ->
124
println("Argument $index: $arg")
125
}
126
127
// Use dependencies from local files
128
// The LocalFilesResolver will automatically resolve ./lib/my-library.jar
129
```
130
131
### BindingsScriptTemplateWithLocalResolving
132
133
Script template that provides map-based variable bindings and automatic local file dependency resolution.
134
135
```kotlin { .api }
136
@ScriptTemplateDefinition(
137
resolver = LocalFilesResolver::class,
138
scriptFilePattern = ".*\\.kts"
139
)
140
abstract class BindingsScriptTemplateWithLocalResolving(
141
val bindings: Map<String, Any?>
142
)
143
```
144
145
**Usage Example:**
146
147
Scripts using this template can access variables through the bindings map:
148
149
```kotlin
150
// In a .kts script file
151
@file:DependsOn("./utils/helper.jar")
152
153
// Access variables from bindings
154
val userName = bindings["user"] as? String ?: "Unknown"
155
val config = bindings["config"] as? Map<String, Any?> ?: emptyMap()
156
157
println("Running script for user: $userName")
158
println("Configuration: $config")
159
160
// Process data using bindings
161
val inputData = bindings["data"] as? List<Any> ?: emptyList()
162
val processed = inputData.map { /* process item */ }
163
```
164
165
## Template Annotations
166
167
Script templates use annotations to define their behavior and dependency resolution:
168
169
```kotlin { .api }
170
@Target(AnnotationTarget.CLASS)
171
annotation class ScriptTemplateDefinition(
172
val resolver: KClass<out ScriptDependenciesResolver> = ScriptDependenciesResolver::class,
173
val scriptFilePattern: String = ".*"
174
)
175
```
176
177
## Working with Templates
178
179
Templates are typically used by script engines automatically, but can also be referenced when configuring custom script environments:
180
181
```kotlin
182
import org.jetbrains.kotlin.script.jsr223.KotlinJsr223JvmLocalScriptEngineFactory
183
import org.jetbrains.kotlin.script.jsr223.KotlinStandardJsr223ScriptTemplate
184
185
// The template class name is used when creating script engines
186
val templateClassName = KotlinStandardJsr223ScriptTemplate::class.qualifiedName!!
187
188
// Script engines use templates internally
189
val factory = KotlinJsr223JvmLocalScriptEngineFactory()
190
val engine = factory.scriptEngine
191
192
// Scripts executed by the engine run in the context of the template
193
val result = engine.eval("""
194
// This script runs with KotlinStandardJsr223ScriptTemplate context
195
println("Template bindings available: ${jsr223Bindings.keys}")
196
42
197
""")
198
```
199
200
## Types
201
202
```kotlin { .api }
203
// From javax.script package
204
interface Bindings : MutableMap<String, Any?>
205
206
// From kotlin.script.templates package
207
abstract class ScriptTemplateWithBindings(val bindings: Bindings)
208
209
// From kotlin.script.dependencies package
210
interface ScriptDependenciesResolver {
211
fun resolve(
212
script: ScriptContents,
213
environment: Map<String, Any?>?,
214
report: (ReportSeverity, String, ScriptContents.Position?) -> Unit,
215
previousDependencies: KotlinScriptExternalDependencies?
216
): Future<KotlinScriptExternalDependencies?>
217
}
218
```