问题
How can I make REPL to import packages given in commnad line?
Sample:
scala -someMagicHere "import sys.error"
scala> :imports
1) import scala.Predef._ (162 terms, 78 are implicit)
2) import sys.error (2 terms)
scala> _
PS: It is not a duplicate. I want automated solution, not manually pasting some code every time I run REPL. Also I don't want to use SBT just for running one command in REPL after its start.
回答1:
Stick it in a file.
apm@mara:~/tmp$ scala -i imports.script
Loading imports.script...
import sys.error
Welcome to Scala version 2.10.2 (OpenJDK 64-Bit Server VM, Java 1.7.0_25).
Type in expressions to have them evaluated.
Type :help for more information.
scala> :impo
1) import scala.Predef._ (162 terms, 78 are implicit)
2) import sys.error (2 terms)
Edit:
I think you get bonus points for finding or otherwise provoking or inducing a bug:
apm@mara:~/tmp$ scala -e "import sys.error"
java.lang.ClassNotFoundException: Main
回答2:
I wrote a script to automatize the command line param to file thing (based on A from som-snytt). It's tested on win 7 with MSYS, but it should work on Linux as well.
bash-3.1$ repl "import sys.error"
Loading C:\Users\xxx\AppData\Local\Temp\tmp.GgEjauEqwz...
import sys.error
Welcome to Scala version 2.10.0 (Java HotSpot(TM) Client VM, Java 1.7.0_07).
Type in expressions to have them evaluated.
Type :help for more information.
scala> :impo
1) import scala.Predef._ (162 terms, 78 are implicit)
2) import sys.error (2 terms)
#!/bin/bash
function crash {
echo "Error: $1"
exit 10
}
if [ $# -ne 1 ]; then
echo "Script requires one parameter."
exit 1
fi
t=$(mktemp) || crash "Unable to create a temp file."
[ ${#t} -lt 1 ] && crash "Suspiciously short file name, aborting."
trap "rm -f -- '$t'" EXIT
echo "$1" > "$t"
scala -i "$t" || crash "Something wrong with scala binary."
rm -f -- "$t"
trap - EXIT
exit
来源:https://stackoverflow.com/questions/18509116/how-to-add-imports-to-repl-from-command-line