Scripting with Scala: How to launch an uncompiled script?

前端 未结 2 1178
我寻月下人不归
我寻月下人不归 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 06:05

    I don't use python, but in Scala, the most scripty thing I can do is this:

    thinkpux:~/proj/mini/forum > echo 'println(" 3 + 4 = " + (3 + 4))' | scala 
    Welcome to Scala version 2.10.2 (Java HotSpot(TM) Server VM, Java 1.7.0_09).
    Type in expressions to have them evaluated.
    Type :help for more information.
    
    scala> println(" 3 + 4 = " + (3 + 4))
     3 + 4 = 7
    
    scala> thinkpux:~/proj/mini/forum > 
    

    However, afterwards, I don't have visual feedback in the bash, so I have to call 'clear'.

    But there is no problem in writing a script and executing that:

    thinkpux:~/proj/mini/forum > echo 'println(" 3 + 4 = " + (3 + 4))' > print7.scala 
    thinkpux:~/proj/mini/forum > scala print7.scala 
     3 + 4 = 7
    

    Then, there aren't issues with the shell.

    With an enclosing class, the code wouldn't be executed:

    thinkpux:~/proj/mini/forum > echo -e 'class Foo {\nprintln(" 3 + 4 = " + (3 + 4))\n}\n'
    class Foo {
    println(" 3 + 4 = " + (3 + 4))
    }
    
    thinkpux:~/proj/mini/forum > scala Foo.scala 
    thinkpux:~/proj/mini/forum > cat Foo.scala 
    class Foo {
    println(" 3 + 4 = " + (3 + 4))
    }
    

    But with instatiating a class, you can execute code in it, without using the wellknown (hope so) 'main' way:

    thinkpux:~/proj/mini/forum > echo -e 'class Foo {\nprintln(" 3 + 4 = " + (3 + 4))\n}\nval foo = new Foo()'  > Foo.scala
    thinkpux:~/proj/mini/forum > cat Foo.scala 
    class Foo {
    println(" 3 + 4 = " + (3 + 4))
    }
    val foo = new Foo()
    thinkpux:~/proj/mini/forum > scala Foo.scala 
     3 + 4 = 7
    

提交回复
热议问题