Experimenting with Scala Worksheets

In the previous chapters, we had run the REPL as an interactive environment to experiment and get immediate feedback when entering the Scala syntax. This allowed us to very quickly write some small algorithms and get the right syntax to make things work. Although the SBT console provides programmers with a :replay command to rerun what has already been written in the session, wouldn't it be nice to be able to save our experiments for later use, as part of our project ? This is exactly what Scala Worksheets are all about.

Scala Worksheet is an innovative feature of the Scala support for Eclipse that brings an interactive environment, that is, a REPL in the context of a project. This feature is also now available on the Scala support for IntelliJ.

Let's go to our small servlet sample in Eclipse to try it out.

To start a worksheet, right-click on any package or source file and navigate to New | Scala Worksheet (or if not present in the drop-down list, navigate to Other... | Scala Wizards | Scala Worksheet), as shown in the following screenshot:

Experimenting with Scala Worksheets

We will choose, for example, the current com.samples package. Click on Next and enter a name for your worksheet: experiment.

This will create a file named experiment.sc that is saved within the source code but as it is not a .scala file, it will not be in conflict with the rest of our current code base nor be present in the deployed .jar archive.

The default page looks like the following code snippet:

packagecom.samples

object experiment {
  println("Welcome to the Scala worksheet")       > Welcome to the Scala worksheet
}

Everything after the > sign on each statement is the result of the evaluation that gets (re)evaluated as soon as you save the Worksheet file. You may try out a few statements, for instance, by replacing the println statement with a few lines, as follows:

object experiment {

  val number = 1 + 2

  List(1,2,3,3,3,4) filter (x => x < 4) distinct

  case class Customer(name:String)

  Customer("Helen")

  new SimpleServlet() 
}

As soon as you save it (Ctrl + S), the style sheet will display statement evaluations on the right-hand side as shown in the following screenshot:

Experimenting with Scala Worksheets
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.137.7