0
# REPL and Scripting
1
2
REPL (Read-Eval-Print Loop) functionality for interactive Scala development, script execution capabilities, and JSR-223 scripting engine integration.
3
4
## Capabilities
5
6
### REPL Driver
7
8
Core REPL engine providing interactive compilation and execution capabilities for Scala code.
9
10
```scala { .api }
11
/**
12
* REPL compilation and execution engine
13
* Provides interactive Scala code evaluation with state preservation
14
*/
15
class ReplDriver {
16
/**
17
* Initialize REPL with default settings
18
* Sets up compilation context and execution environment
19
*/
20
def initialize(): Unit
21
22
/**
23
* Initialize REPL with custom settings
24
* @param settings Compiler settings for REPL compilation
25
* @param classpath Additional classpath entries for REPL
26
*/
27
def initialize(settings: Settings, classpath: List[String]): Unit
28
29
/**
30
* Evaluate a line of Scala code
31
* Compiles and executes the code, maintaining state between evaluations
32
* @param line Scala code to evaluate
33
* @return ReplResult containing evaluation outcome and value
34
*/
35
def eval(line: String): ReplResult
36
37
/**
38
* Reset REPL state
39
* Clears all previously defined symbols and imported names
40
*/
41
def reset(): Unit
42
43
/**
44
* Get current REPL context
45
* @return Compilation context with current REPL state
46
*/
47
def currentContext: Context
48
49
/**
50
* Add import to REPL scope
51
* @param importPath Import path to add (e.g., "scala.collection.mutable._")
52
*/
53
def addImport(importPath: String): Unit
54
55
/**
56
* Get REPL history
57
* @return List of previously evaluated expressions
58
*/
59
def history: List[String]
60
61
/**
62
* Get defined symbols in REPL
63
* @return Map of symbol names to their types
64
*/
65
def definedSymbols: Map[String, String]
66
67
/**
68
* Execute multi-line code block
69
* @param code Multi-line Scala code to execute
70
* @return ReplResult containing execution outcome
71
*/
72
def executeBlock(code: String): ReplResult
73
}
74
```
75
76
**Usage Examples:**
77
78
```scala
79
import dotty.tools.repl.ReplDriver
80
81
val repl = new ReplDriver
82
repl.initialize()
83
84
// Basic evaluation
85
val result1 = repl.eval("val x = 42")
86
println(result1.value) // prints: 42
87
88
val result2 = repl.eval("x * 2")
89
println(result2.value) // prints: 84
90
91
// Add imports
92
repl.addImport("scala.collection.mutable._")
93
val result3 = repl.eval("val buffer = ListBuffer(1, 2, 3)")
94
95
// Multi-line code
96
val multiLine = """
97
|def factorial(n: Int): Int =
98
| if n <= 1 then 1
99
| else n * factorial(n - 1)
100
|
101
|factorial(5)
102
""".stripMargin
103
104
val result4 = repl.executeBlock(multiLine)
105
println(result4.value) // prints: 120
106
```
107
108
### REPL Main Entry Point
109
110
Command-line entry point for starting the interactive REPL session.
111
112
```scala { .api }
113
/**
114
* REPL main entry point
115
* Provides command-line interface for starting interactive sessions
116
*/
117
object repl.Main {
118
/**
119
* Start interactive REPL session
120
* @param args Command-line arguments for REPL configuration
121
*/
122
def main(args: Array[String]): Unit
123
124
/**
125
* Start REPL with custom configuration
126
* @param settings REPL-specific settings
127
* @param initialCommands Commands to execute at startup
128
*/
129
def startRepl(settings: ReplSettings, initialCommands: List[String]): Unit
130
131
/**
132
* Run REPL in batch mode (non-interactive)
133
* @param commands List of commands to execute
134
* @return List of results from command execution
135
*/
136
def runBatch(commands: List[String]): List[ReplResult]
137
}
138
```
139
140
**Usage Examples:**
141
142
```bash
143
# Start interactive REPL
144
scala3-repl
145
146
# Start REPL with custom classpath
147
scala3-repl -classpath "lib/*:target/classes"
148
149
# Start REPL with initial imports
150
scala3-repl -i "import mypackage._"
151
```
152
153
```scala
154
// Programmatic REPL usage
155
import dotty.tools.repl.Main
156
157
val settings = ReplSettings(
158
classpath = List("lib/mymath.jar"),
159
verbose = true
160
)
161
162
val initialCommands = List(
163
"import mymath._",
164
"val pi = 3.14159"
165
)
166
167
Main.startRepl(settings, initialCommands)
168
```
169
170
### Script Engine (JSR-223)
171
172
JSR-223 ScriptEngine implementation for integrating Scala compilation and execution into Java applications.
173
174
```scala { .api }
175
/**
176
* JSR-223 ScriptEngine implementation
177
* Provides standardized scripting interface for Java integration
178
*/
179
class ScriptEngine extends javax.script.ScriptEngine {
180
/**
181
* Evaluate Scala script from string
182
* @param script Scala code to evaluate
183
* @return Result of script evaluation
184
*/
185
def eval(script: String): Object
186
187
/**
188
* Evaluate Scala script from string with bindings
189
* @param script Scala code to evaluate
190
* @param bindings Variable bindings to make available in script
191
* @return Result of script evaluation
192
*/
193
def eval(script: String, bindings: javax.script.Bindings): Object
194
195
/**
196
* Evaluate Scala script from Reader
197
* @param reader Reader containing Scala code
198
* @return Result of script evaluation
199
*/
200
def eval(reader: java.io.Reader): Object
201
202
/**
203
* Create new bindings for script variables
204
* @return Fresh Bindings instance
205
*/
206
def createBindings(): javax.script.Bindings
207
208
/**
209
* Get script engine factory
210
* @return ScriptEngineFactory for this engine
211
*/
212
def getFactory(): javax.script.ScriptEngineFactory
213
214
/**
215
* Get current script context
216
* @return ScriptContext containing engine state
217
*/
218
def getContext(): javax.script.ScriptContext
219
220
/**
221
* Set script context
222
* @param context New script context to use
223
*/
224
def setContext(context: javax.script.ScriptContext): Unit
225
}
226
```
227
228
**Usage Examples:**
229
230
```java
231
// Java usage of Scala ScriptEngine
232
import javax.script.*;
233
234
ScriptEngineManager manager = new ScriptEngineManager();
235
ScriptEngine scalaEngine = manager.getEngineByName("scala");
236
237
// Basic script evaluation
238
Object result = scalaEngine.eval("42 + 8");
239
System.out.println(result); // prints: 50
240
241
// Script with bindings
242
Bindings bindings = scalaEngine.createBindings();
243
bindings.put("x", 10);
244
bindings.put("y", 20);
245
Object sum = scalaEngine.eval("x + y", bindings);
246
System.out.println(sum); // prints: 30
247
248
// Multi-line script
249
String script = """
250
def fibonacci(n: Int): Int =
251
if n <= 1 then n
252
else fibonacci(n-1) + fibonacci(n-2)
253
254
fibonacci(10)
255
""";
256
Object fib = scalaEngine.eval(script);
257
System.out.println(fib); // prints: 55
258
```
259
260
### REPL Commands
261
262
Built-in REPL commands for interactive development and debugging.
263
264
```scala { .api }
265
/**
266
* REPL command system
267
* Provides meta-commands for REPL interaction and introspection
268
*/
269
object ReplCommand {
270
/**
271
* Show help for available commands
272
*/
273
def help(): String
274
275
/**
276
* Show type of expression
277
* @param expr Expression to get type for
278
* @return String representation of the type
279
*/
280
def showType(expr: String): String
281
282
/**
283
* Show definition of symbol
284
* @param name Symbol name to show definition for
285
* @return String containing symbol definition
286
*/
287
def showDefinition(name: String): String
288
289
/**
290
* List currently defined symbols
291
* @return List of symbol names and their types
292
*/
293
def listSymbols(): List[(String, String)]
294
295
/**
296
* Show REPL history
297
* @return List of previously entered commands
298
*/
299
def showHistory(): List[String]
300
301
/**
302
* Load Scala file into REPL
303
* @param filename Path to Scala file to load
304
* @return Result of loading the file
305
*/
306
def loadFile(filename: String): ReplResult
307
308
/**
309
* Save REPL session to file
310
* @param filename Path to save session to
311
*/
312
def saveSession(filename: String): Unit
313
314
/**
315
* Execute shell command
316
* @param command Shell command to execute
317
* @return Output from shell command
318
*/
319
def shell(command: String): String
320
}
321
```
322
323
**Interactive Usage:**
324
325
```scala
326
scala> :help
327
Available commands:
328
:type <expr> show the type of an expression
329
:def <name> show definition of a name
330
:list list defined names and their types
331
:history show command history
332
:load <file> load and execute a Scala file
333
:save <file> save session to file
334
:! <command> execute shell command
335
336
scala> val numbers = List(1, 2, 3, 4, 5)
337
val numbers: List[Int] = List(1, 2, 3, 4, 5)
338
339
scala> :type numbers.map(_ * 2)
340
List[Int]
341
342
scala> :def numbers
343
val numbers: List[Int]
344
345
scala> :list
346
val numbers: List[Int]
347
348
scala> :load "myScript.scala"
349
Loading myScript.scala...
350
```
351
352
### Scripting Utilities
353
354
Utilities for script execution and file processing in REPL and scripting contexts.
355
356
```scala { .api }
357
/**
358
* Scripting utilities for file processing and execution
359
*/
360
object ScriptingUtils {
361
/**
362
* Compile and execute Scala script file
363
* @param scriptPath Path to Scala script file
364
* @param args Arguments to pass to script
365
* @return Exit code from script execution
366
*/
367
def executeScript(scriptPath: String, args: Array[String]): Int
368
369
/**
370
* Compile script to bytecode
371
* @param scriptContent Scala script content
372
* @param outputDir Directory to write compiled classes
373
* @return List of generated class files
374
*/
375
def compileScript(scriptContent: String, outputDir: String): List[String]
376
377
/**
378
* Check if file is a valid Scala script
379
* @param filePath Path to file to check
380
* @return True if file appears to be a Scala script
381
*/
382
def isScalaScript(filePath: String): Boolean
383
384
/**
385
* Extract script dependencies from comments
386
* @param scriptContent Script content to analyze
387
* @return List of dependency specifications
388
*/
389
def extractDependencies(scriptContent: String): List[String]
390
391
/**
392
* Resolve script dependencies
393
* @param dependencies List of dependency specifications
394
* @return List of resolved JAR file paths
395
*/
396
def resolveDependencies(dependencies: List[String]): List[String]
397
}
398
```
399
400
## Types
401
402
### ReplResult
403
404
```scala { .api }
405
/**
406
* Result of REPL evaluation
407
*/
408
case class ReplResult(
409
success: Boolean, // Whether evaluation succeeded
410
value: Any, // Result value (if successful)
411
valueType: String, // String representation of result type
412
output: String, // Standard output from evaluation
413
error: Option[String] // Error message (if failed)
414
)
415
```
416
417
### ReplSettings
418
419
```scala { .api }
420
/**
421
* REPL-specific configuration settings
422
*/
423
case class ReplSettings(
424
classpath: List[String] = Nil, // Additional classpath entries
425
imports: List[String] = Nil, // Auto-imports for REPL session
426
verbose: Boolean = false, // Enable verbose output
427
colors: Boolean = true, // Enable syntax coloring
428
prompt: String = "scala> ", // Command prompt string
429
continuationPrompt: String = " | ", // Multi-line continuation prompt
430
maxOutputLines: Int = 1000, // Maximum lines of output to show
431
historyFile: Option[String] = None // Path to history file
432
)
433
```
434
435
### ScriptEngineFactory
436
437
```scala { .api }
438
/**
439
* Factory for creating Scala script engines
440
*/
441
class ScriptEngineFactory extends javax.script.ScriptEngineFactory {
442
def getEngineName(): String = "Scala Script Engine"
443
def getEngineVersion(): String = "3.7.0"
444
def getLanguageName(): String = "Scala"
445
def getLanguageVersion(): String = "3.7.0"
446
def getNames(): java.util.List[String] = java.util.List.of("scala", "scala3")
447
def getMimeTypes(): java.util.List[String] = java.util.List.of("application/scala")
448
def getExtensions(): java.util.List[String] = java.util.List.of("scala", "sc")
449
}
450
```