Simple I/O

Scala's implicit Console object allows programmers to write to the project's console window.

Scala's io.StdIn object allows programmers to read from the console window.

scala> var num1 = scala.io.StdIn.readDouble
3.14
num1: Double = 3.14

scala> Console.println("2 * num1 = " + 2 * num1)
2 * num1 = 6.28

Example: a console object

import scala.io._

object console {
 
  def execute(cmmd: String): String = {
    if (cmmd.length < 1) throw new Exception("Empty command invalid")
    "you typed: " + cmmd
  }
 
  def repl() {
    var cmmd: String = ""
    val prompt = "=> "
    var more = true
    while(more) {
      try {
        print(prompt)
        cmmd = StdIn.readLine
        if (cmmd == "quit") more = false
        else {
          val result = execute(cmmd)
          println(result)
        }
      } catch {
        case e: Exception => println(e)
      }
    }
    println("bye")
  }
 
   def main(args: Array[String]): Unit = { repl }
}

Sample output

=> hello world
you typed: hello world
=> 23 + 45
you typed: 23 + 45
=>
java.lang.Exception: Empty command invalid
=> quit
bye

Notes

·       Console is a singleton object. (We don't need multiple consoles.)

·       Console is reusable, just replace the execute method.

·       The execute method may throw an exception if the input command is invalid.

·       The exception is caught inside the while loop. Hence users aren't bounced out if they accidentally typed an invalid command.

·       Break and continue are not available in Scala.

 

Example: File Reader

import scala.io._

object fileReader {
 
  def execute(cmmd: String) = {
    if (cmmd.length < 1) throw new Exception("Empty command invalid")
    "you typed: " + cmmd
   }
 
 
   private def executeFile(fileName: String) {

     var more = true
   
     for (line <- Source.fromFile(fileName).getLines if more) {
       try {
         println(execute(line))
       } catch {
          case e: Exception => {
              println(e)
              more = false
          }
       }
     }
   }
  
   def main(args: Array[String]): Unit = {
     if (args.length > 0)
       try {
         executeFile(args(0))
       } catch  {
         case e: Exception => {
              println(e)
            }
       }
   }
}

greetings

hello Mercury
hello Venus
hello Earth
hello Mars
hello Jupiter
hello Saturn
hello Uranus
hello Neptune

hello Pluto
hello etc.

output

you typed: hello Mercury
you typed: hello Venus
you typed: hello Earth
you typed: hello Mars
you typed: hello Jupiter
you typed: hello Saturn
you typed: hello Uranus
you typed: hello Neptune
java.lang.Exception: Empty command invalid

Notes