Scripting with Scala: How to launch an uncompiled script?

前端 未结 2 1048
我寻月下人不归
我寻月下人不归 2021-02-06 05:31

Apart from serious performance problems, Scala is a very powerful language. Therefore I am now using it frequently for scripted tasks inside Bash. Is there a way to just execute

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-06 05:59

    The scala man page provides some examples on how to run Scala code fragments as if they were a script, for both Windows and non-Windows platforms (below examples copied from the man page):

    Unix

       #!/bin/sh
       exec scala "$0" "$@"
       !#
       Console.println("Hello, world!")
       argv.toList foreach Console.println
    

    Windows

       ::#!
       @echo off
       call scala %0 %*
       goto :eof
       ::!#
       Console.println("Hello, world!")
       argv.toList foreach Console.println
    

    To speed up subsequent runs you can cache the compiled fragment with the -savecompiled option:

       #!/bin/sh
       exec scala -savecompiled "$0" "$@"
       !#
       Console.println("Hello, world!")
       argv.toList foreach Console.println
    

    Update: as of Scala 2.11 (as noted in this similar answer), you can now just do this on Unix:

    #!/usr/bin/env scala
    println("Hello, world!")
    println(args.mkString(" "))
    

提交回复
热议问题