catch32
catch32

Reputation: 18582

can't run .scala file from REPL?

I'm newly at Scala.

I want to run function which is wrote at my file while.scala:

def whileLoop {
    var i = 1
    while(i <= 3) {
        println(i)
        i += 1
    }
}
whileLoop

here is how it looks at REPL:

scala> scala /home/nazar/Downloads/while.scala
<console>:1: error: illegal start of simple expression

If I understood right from book. I need to specify .scala file location and run with:

scala /path/to/file.scala

Why it fails?

Here is snippet from book:

You can run the code like this:
batate$ scala code/scala/while.scala
1
2
3

UPDATE:

I tried options :load it works, but when I want to run another file for_loop.scala:

def forLoop {
    println( "for loop using Java-style iteration" )
    for(i <- 0 until args.length) {
        println(args(i))
    }
}    
forLoop

it fails:

scala> :load /home/nazar/Downloads/for_loop.scala
Loading /home/nazar/Downloads/for_loop.scala...
<console>:9: error: not found: value args
           for(i <- 0 until args.length) {
                            ^
<console>:8: error: not found: value forLoop
              forLoop
              ^

scala> :load /home/nazar/Downloads/for_loop.scala hello scala
That file does not exist

How to solve this trouble?

Upvotes: 2

Views: 1641

Answers (2)

elm
elm

Reputation: 20415

In order to use command line arguments (via args) it is needed to extend App or more commonly to define a principal or main method in an object, namely a def main(args: Array[String]) method, which defines an entry point to the program. Consider for instance

object AnyName extends App {
  def forLoop {
    println( "for loop using Java-style iteration" )
    for(i <- 0 until args.length) {
        println(args(i))
    }
  }
  forLoop
}

AnyName.main(Array("first","second"))

Try to load it from REPL. The other approach is thus,

object AnyName {
  def main(args: Array[String]) {
    println( "for loop using Java-style iteration" )
    for(i <- 0 until args.length) {
        println(args(i))
    }
  }
}

AnyName.main(Array("first","second"))

In this latter example, note the scope of args, bound to the parameter in main.

Upvotes: 2

Randall Schulz
Randall Schulz

Reputation: 26486

You do it like this, from the shell / command line, not from within the REPL (% is nominal shell prompt):

% scala MyScalaScriptName.scala

You did this:

% scala
scala> scala while.scala
<console>:1: error: illegal start of simple expression

The only thing known within the Scala REPL is Scala code itself and a few built-in special commands. However, one of them will do what you want:

% cd
% scala
scala> :load Downloads/while.scala
Loading Downloads/while.scala
1
2
3

Upvotes: 5

Related Questions